gpt4 book ai didi

javascript - 通过复选框在 Redux 状态中切换 True 和 False

转载 作者:行者123 更新时间:2023-11-30 14:44:34 25 4
gpt4 key购买 nike

这里是 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
})

和 reducer :

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)

如果你的store初始状态是

{
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)

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com