【问题标题】:react-redux: why do I get _this.props.incrementCounter is not a function?react-redux:为什么我得到 _this.props.incrementCounter is not a function?
【发布时间】:2018-08-23 16:08:08
【问题描述】:

刚从 react/redux 开始。尝试实现一个与动作挂钩的 Counter 组件:

export class Counter extends Component {
    constructor(props) {
        super(props);
      }

    handleClick = () => {
        this.props.incrementCounter();
    }

    render() {
        return (
            <div onClick={this.handleClick}>
                hello this is counter:{this.props.counter}
            </div>
        )
    }
}

const mapStateToProps = (state) => ({
    counter: state
})

export default connect(mapStateToProps, { incrementCounter })(Counter)

这是 index.js 的一部分:

ReactDOM.render(<Provider store={store}>
    <App />
</Provider>, document.getElementById('root'));

但是,当我运行应用程序时,单击“hello”div 时出现错误?

错误: _this.props.incrementCounter 不是函数

为什么会出现这个错误,好像 props 没有正确传递?

更多代码见:github

【问题讨论】:

    标签: javascript reactjs react-redux


    【解决方案1】:

    你需要使用一个函数作为第二个参数,比如:

    connect(mapStateToProps, dispatch =&gt; ({ incrementCounter }))(Counter)

    【讨论】:

    • “incrementCounter”在哪里定义?就像一般情况下你会有类似 `dispatch => ({ incrementCounter: () => dispatch(methodName()) })
    • incrementCounter 有可能是 undefined atm?
    猜你喜欢
    • 1970-01-01
    • 2020-01-20
    • 2019-05-08
    • 1970-01-01
    • 2018-10-28
    • 2020-03-26
    • 2021-10-02
    • 2020-03-01
    • 1970-01-01
    相关资源
    最近更新 更多