在React + Redux中动态设置表单字段值
问题描述:
我的应用商店有一个store.authState
子树。在这个子树中,有三件事,一个是authToken
,一个isFetching
布尔值,最重要的是一个fields
对象。我的表单包含两个字段:username
和password
。在React + Redux中动态设置表单字段值
我创建了一个叫做SET_FORM_FIELD_VALUE
一个行动,这应该产生和因为它们是由用户修改更新每个字段的状态。
我想我的SET_FORM_FIELD_VALUE
更新fields
对象。如果用户在两个username
和password
领域通常罢了,我store.authState
应该是这样的:
{
authToken: undefined,
isFetching: false,
fields: {
username: "Brachamul",
password: "azerty123"
}
}
然而,似乎是我当前的代码实际上只是覆盖一切,我结束了:
{
field: {
username: "Brachamul"
}
}
该字段中的数据根据我上次编辑的字段而变化。它是用户名或密码。
这里是我的代码:
switch (action.type) {
case 'SET_FORM_FIELD_VALUE':
let field = {} // create a "field" object that will represent the current field
field[action.fieldName] = action.fieldValue // give it the name and value of the current field
return { ...state.fields, field }
我怎样才能改变它来解决我的问题?
答
你的回报是错了,应该是这样的
switch (action.type) {
case 'SET_FORM_FIELD_VALUE':
return {
...state,
fields: {
...state.fields,
[action.fieldName] : action.fieldValue
}
}
}
希望它能帮助。