gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'props' of undefined (reactjs) (very simpel)

转载 作者:行者123 更新时间:2023-11-30 11:14:37 25 4
gpt4 key购买 nike

我遵循了这个关于 redux 的初学者教程:text , vid .

除增量按钮外,一切正常。当我点击递增按钮时,出现此错误:

Uncaught TypeError: Cannot read property 'props' of undefined

看看会发生什么: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);

最佳答案

编辑:

其实有两个问题:

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

第二个是,使用 react-reduxconnect 函数,您需要将 redux dispatch 函数映射到一个 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);

关于javascript - 未捕获的类型错误 : Cannot read property 'props' of undefined (reactjs) (very simpel),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52120253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com