【问题标题】:React Redux connect API does not inject dispatch propertyReact Redux 连接 API 不注入调度属性
【发布时间】:2016-04-11 21:01:54
【问题描述】:

我使用 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”未定义的错误。

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    您没有使用连接的组件,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 函数尝试对一个对象而不是内部的整数进行递增或递减。

    【讨论】:

    • 谢谢。这样可行。也感谢您指出其他两个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2017-09-26
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    相关资源
    最近更新 更多