首页 > 解决方案 > 未捕获的类型错误:无法读取未定义的属性“道具”(reactjs)(非常简单)

问题描述

我遵循了这个关于 redux 的初学者教程:textvid

除增量按钮外,一切正常。当我单击增量按钮时,我收到此错误:

未捕获的类型错误:无法读取未定义的属性“道具”

看看会发生什么:gif

为什么我在执行“mapStateToProps”时会出现该错误?

索引.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import Test_left from './eo_app.jsx';
import { Provider } from 'react-redux';
import { createStore } from "redux";

const initialState = {
    count: 21
};

const reducer = (state = initialState, action) => {
    console.log('reducer', action);

    switch (action.type) {
        case 'INCREMENT':
            return { count: 55 };
        default:
                return state;
    }
};

const store = createStore(reducer);


const App = () => (
  <Provider store={store}>
    <Test_left />
  </Provider>
);

ReactDOM.render(<App />, document.getElementById('target'));

//// store.dispatch({type: 'INCREMENT' }); this will work as expected

eo_app.jsx

import React from 'react';
import { connect } from 'react-redux';


class Test_left extends React.Component {
    constructor(props) {
        super(props);
    }

    increment () {
    this.props.dispatch({ type: 'INCREMENT' }); // <== ERROR IS RAISED HERE
  }

    render() {
        console.log('props:', this.props)
        return (
                <React.Fragment>
                    <h1> WE GOT RENDERED </h1>
                    <h1>{this.props.count}</h1>
                    <button onClick={this.increment}> Increment </button>
                </React.Fragment>
        )
    };
}

const mapStateToProps = state => ({
    count: state.count
})

export default connect(mapStateToProps)(Test_left);

标签: javascriptreactjsreduxreact-redux

解决方案


编辑:

其实有两个问题:

首先是您需要将您的increment函数绑定到类本身。这是一个常见的“陷阱”,您可以在此处阅读 - https://reactjsnews.com/es6-gotchas

第二个是,with函数react-reduxconnect需要将reduxdispatch函数映射到一个prop。这是通过您在connect调用中传递的第二个函数完成的:mapDispatchToProps.

你的可能看起来像:

const mapDispatchToProps = dispatch => ({
    handleClick: () => dispatch({ type: 'INCREMENT' })
});

通过这两个更改,您的组件将看起来像

class Test_left extends React.Component {
    constructor(props) {
        super(props);

        // Bind `increment` to this class's scope
        this.increment = this.increment.bind(this);
    }

    increment () {
        // Use newly created prop function to dispatch our action to redux
        this.props.handleClick();
    }

    // ...
}

const mapStateToProps = state => ({
    count: state.count
});
const mapDispatchToProps = dispatch => ({
    handleClick: () => dispatch({ type: 'INCREMENT' })
});

export default connect(mapStateToProps, mapDispatchToProps)(Test_left);

推荐阅读