![](/img/trans.png)
[英]My checkbox is not pre-filled with value present in redux state i.e true or false
[英]Toggling True and False in Redux State via a Checkbox
总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;
}
}
我的问题是:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.