Total React / Redux noob here;在我的应用程序中,我有一个表单复选框,应该在我的状态中将选项设置为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;
}
}
我的问题是:
getState()
是标准方式吗?任何输入都表示赞赏!
答案 0 :(得分:2)
1)
如果商店的初始状态为
{
formOptions: {
currentAddress: true,
isEmployed: true
// ...
}
}
然后在reducer中不返回
{
...state.formOptions
}
因为这会返回一个与初始结构不同的状态
{
currentAddress: true,
isEmployed: true
// ...
}
请在此处阅读有关广告运营商行为的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
相反,您的reducer应该看起来像
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)
您可能希望使用React组件绑定Redux存储,以便能够在React组件props中传递Redux数据。完整说明可在此处获取:https://redux.js.org/basics/usage-with-react