javascript - 未捕获的类型错误:无法读取未定义的属性“道具”(reactjs)(非常简单)
问题描述
我遵循了这个关于 redux 的初学者教程:text,vid。
除增量按钮外,一切正常。当我单击增量按钮时,我收到此错误:
未捕获的类型错误:无法读取未定义的属性“道具”
看看会发生什么: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
函数绑定到类本身。这是一个常见的“陷阱”,您可以在此处阅读 - https://reactjsnews.com/es6-gotchas
第二个是,with函数react-redux
,connect
需要将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);
推荐阅读
- vba - MS Access VBA 查看条件格式规则当前是否对控件处于活动状态
- r - 如何在R中使用charts.performanceanalytics绘制累积回报图表
- python-asyncio - 如何使用 session.get() 将标头传递给异步
- google-apps-script - 无法通过脚本获得范围内的特定值
- azure-data-explorer - Kusto - bin() 如何总结时间戳
- asp.net-core - 没有为 Vue.Js + ASP.Net Core MVC 应用程序加载 Vue 组件
- python - 如何通过tensorflow将多个学习数据输入model.fit()
- r - R 中的 Memory.limit 与 memory.size
- javascript - 如何在nodejs中列出路径文件名
- bluetooth-lowenergy - 如何修改 BLE gatt 服务器配置文件