javascript - React: mapStateToProps - 我如何获得状态?
问题描述
我使用 mapStateToProps、mapDispatchToProps 将函数和状态传递给 myComponent,我可以获取函数但无法获取状态。我的代码如下所示:
const mapStateToProps = (state) => ({
...state.editor
});
const mapDispatchToProps = (dispatch) => ({
onLoad: (payload) => dispatch(actionCreators.myFunc(payload)),}
});
function myComponent({errors, match, onLoad}) {
//function myComponent({errors, match, onLoad, state}) { //state undefined
//function myComponent({errors, match, onLoad}, state) { //state undefined
// How do I get state here?
console.log(state) //always undefined
console.log(state.editor) //undefined
console.log(editor) //undefined
}
export default connect(mapStateToProps, mapDispatchToProps)(myComponent);
解决方案
在下面更改您的mapStateToProps
喜欢
const mapStateToProps = (state) => ({
editor:state.editor
});
通常的例子Functional component
是
function YourComponent({ yourProp }) {
return <p>{yourProp}</p>
}
function mapStateToProps(state) {
return { yourProp: state.yourProp };
}
export default connect(mapStateToProps)(YourComponent);
推荐阅读
- javascript - Javscript Promises:如何结合 .fetch() .then() 和 all()
- node.js - app/.heroku/node/bin/node 占用大量内存并崩溃
- c# - 如何将文本串起来以一个接一个地显示段落中的单词?
- c# - 为什么 List.Sum() 与 foreach 相比表现不佳?
- python - 如何在 ipywidgets 上获取文件上传的路径?
- php - 如何使用ajax jquery遍历json响应数据?
- c++ - 复制构造函数和赋值运算符 (=) 之间的 C++ 代码可重用性
- c# - 无法使用桥接网络模式从 docker 容器连接到远程 SQL 服务器
- groovy - 使用“|”执行 aws 命令时无法在 Groovy 中获得输出 和“sed”
- java - Java JUnit Test Simulate Next 计算出的数字