React/Redux:mapStateToProps 实际上并未将状态映射到道具 [英] React / Redux: mapStateToProps not actually mapping state to props

查看:46
本文介绍了React/Redux:mapStateToProps 实际上并未将状态映射到道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中使用 React 和 Redux,但在实现启用/禁用按钮的功能时遇到问题.我已经能够:

I'm using React and Redux on a project, and I'm having problems implementing a feature to enable/disable a button. I've been able to:

  • 触发一个方法
  • 让该方法触发动作创建者
  • 发送一个动作
  • 在 reducer 中捕获该操作并创建一个新的更新状态
  • 在 Redux DevTools 中查看更新的状态

然而,启用/禁用功能仍然不起作用,因为看起来 mapStateToPropsconnect 实际上并没有将状态映射到道具.我正在跟踪 canSubmit,它在 state 内发生变化,但在 props 中是 undefined.成功将状态映射到道具我缺少什么?

However, the enable/disable functionality still doesn't work, as it seems that mapStateToProps and connect aren't actually mapping the state to the props. I'm tracking canSubmit, which changes within the state but is undefined in the props. What am I missing to successfully map the state to the props?

相关代码:

UserFormView.js

UserFormView.js

const mapStateToProps = (state) => ({
  routerState: state.router,
  canSubmit: state.canSubmit
});
const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(ActionCreators, dispatch)
});

class UserFormView extends React.Component {

...

}

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

操作:

export function enableSubmit(payload) {
  return {
    type: ENABLE_SUBMIT,
    payload: payload
  };
}

export function disableSubmit(payload) {
  return {
    type: DISABLE_SUBMIT,
    payload: payload
  };
}

Reducer(使用 createReducer 辅助函数):

Reducer (using a createReducer helper function):

const initialState = {
  canSubmit: false
};

export default createReducer(initialState, {

  [ENABLE_SUBMIT]: (state) => {
    console.log('enabling');
    return Object.assign({}, state, {
      canSubmit: true
    });
  },

  [DISABLE_SUBMIT]: (state) => {
    console.log('disabling');
    return Object.assign({}, state, {
      canSubmit: false
    });
  }

});

推荐答案

似乎您没有使用 canSubmit 键创建 reducer.这取决于你的商店配置,更具体地说——取决于你如何从减少文件中导入默认导出.这里要提到的另一件事,很可能你会有一个名为 canSubmit 的 reducer 和一个键 canSubmit,所以你需要在像 这样的代码中引用它state.canSubmit.canSubmit — 您从 reducer 上的操作处理程序返回对象,而不是简单的 truefalse 布尔值.

Seems like you're not creating reducer with key canSubmit. It depends on your store configuration, to be more specific — on how you import your default export from reduces file. Another thing to mention here, it's likely you'll have reducer with the name canSubmit and a key canSubmit, so you'll need to reference it in code like state.canSubmit.canSubmit — you're returning object from action handlers on reducer, not simple true or false boolean values.

这篇关于React/Redux:mapStateToProps 实际上并未将状态映射到道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆