当前位置 : 主页 > 网页制作 > React >

reactjs – React Redux connect API不会注入dispatch属性

来源:互联网 收集:自由互联 发布时间:2021-06-15
我使用react-redux将React与Redux存储连接起来,并使用“connect”API将“dispatch”属性注入组件.但该组件未收到“dispatch”属性.以下是演示我遇到的问题的代码: "use strict"var React = require('rea
我使用react-redux将React与Redux存储连接起来,并使用“connect”API将“dispatch”属性注入组件.但该组件未收到“dispatch”属性.以下是演示我遇到的问题的代码:

"use strict"

var React = require('react');
var ReactDOM = require('react-dom');
var Redux = require('redux');
var ReactRedux = require('react-redux');
var Provider = ReactRedux.Provider;

function menuManager(state = {count: 0}, action) {
  switch (action.type) {
    case 'ADD':
      return state + 1;
    case 'REMOVE':
      return state - 1;
    default:
      return state;
  }
}

let store = Redux.createStore(menuManager);

let TestLab = React.createClass({
  onRemove: function(itemRemove) {
    // this.props.dispatch undefined.
    this.props.dispatch({type: 'REMOVE'});
  },
  onAdd: function() {
    const { dispatch } = this.props
    // this.props.dispatch undefined.
    this.props.dispatch({type: 'ADD'});
  },
  getInitialState: function() {
    return { count: 0 };
  },
  render: function() {
    return (
        <div>
          <p>Total count: { this.state.count }</p>
          <button type="button" onClick={this.onAdd}>Add Item</button>
        </div>
    );
  }
});

function select(state) {
  return state;
}

ReactRedux.connect(select)(TestLab);

var target = document.createElement('div');
document.body.appendChild(target);
ReactDOM.render(<Provider store={store}><TestLab /></Provider>, target);

当我尝试调用“this.props.dispatch”时,我收到一条错误,“this.props.dispatch”未定义.

您没有使用连接组件connect() returns a new component.

TestLab = ReactRedux.connect(select)(TestLab);
ReactDOM.render(<Provider store={store}><TestLab /></Provider>, target);

您还将遇到其他一些问题,即您正在使用this.state.count而不是this.props.count,并且您的reducer函数会尝试增加或减少对象而不是整数内部.

网友评论