作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这里是 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;
}
}
我的问题是:
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/
我是一名优秀的程序员,十分优秀!