首页 > 解决方案 > 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);

标签: javascriptreactjsredux

解决方案


在下面更改您的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);

推荐阅读