总React / Redux新手在这里;在我的应用程序中,我有一个表单复选框,该复选框应在我的状态下将选项设置为true或false。

这是我的复选框-我不确定如何正确设置此true / false标志:

<input
  type="checkbox"
  onChange={ (e) => this.props.dispatch(setOption({'currentAddress': [true/false flag]})) }
  defaultChecked={ true }
/>


操作-表单上的其他复选框应可重用此操作:

const SET_OPTION = 'SET_OPTION';

export const setOption = (option) => ({
    type: SET_OPTION,
    payload: option
})


减速器:

const initialState = {
  formOptions {
    currentAddress: true,
    isEmployed: true,
    // ...
  }
}

const Reducer = (state = initialState, action) => {
  switch (action.type) {
    case SET_OPTION:
      let option = action.payload
      return { ...state.formOptions, option};
    default:
    return state;
  }
}


我的问题是:


如何在我的状态下在true和false之间切换选项?
以后如何在代码中引用此选项? getState()是标准方式吗?


任何输入表示赞赏!

最佳答案

1)

如果您商店的初始状态是

{
  formOptions: {
    currentAddress: true,
    isEmployed: true
    // ...
  }
}


然后在减速器中不返回

{
  ...state.formOptions
}


因为这将返回看起来与初始结构不同的状态

{
  currentAddress: true,
  isEmployed: true
  // ...
}


在此处阅读有关传播操作员行为的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

相反,您的减速器应该看起来像

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case SET_OPTION:
      return {
        ...state, // copy data in state other than formOptions
        formOptions: {
          ...state.formOptions, // copy other formOptions
          ...action.payload // here you are overwriting the 'currentAddress' property since action.payload = { 'currentAddress': true/false }
        }
      };
    default:
      return state;
  }
};


Reducer只是一个接受state并返回新的state的函数:)

2)

您可能希望将Redux存储与React组件绑定,以便能够在React组件props中传递Redux数据。此处提供完整说明:https://redux.js.org/basics/usage-with-react

关于javascript - 通过复选框在Redux状态下切换是非,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49153146/

10-15 19:05