2016-04-24 30 views
0

我的应用商店有一个store.authState子树。在这个子树中,有三件事,一个是authToken,一个isFetching布尔值,最重要的是一个fields对象。我的表单包含两个字段:usernamepassword在React + Redux中动态设置表单字段值

我创建了一个叫做SET_FORM_FIELD_VALUE一个行动,这应该产生和因为它们是由用户修改更新每个字段的状态。

我想我的SET_FORM_FIELD_VALUE更新fields对象。如果用户在两个usernamepassword领域通常罢了,我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 } 

我怎样才能改变它来解决我的问题?

回答

2

你的回报是错了,应该是这样的

switch (action.type) { 
    case 'SET_FORM_FIELD_VALUE': 
      return { 
        ...state, 
        fields: { 
         ...state.fields, 
         [action.fieldName] : action.fieldValue 
        } 
      } 
} 

希望它能帮助。

相关问题