简体   繁体   English

如何在React和Redux中使几个字段可编辑?

[英]How to make several fields editable in React and Redux?

I have an object in my redux state 我的对象处于还原状态

const obj = {
 name: 'name',
 age: 2,
 place: 0,
}

I show these values on the page but I want to make two of them editable so that the object can be updated. 我在页面上显示了这些值,但我想使其中两个可编辑,以便可以更新对象。

For that I'm basically getting values from two inputs and sending them to my action 为此,我基本上是从两个输入中获取值并将其发送给我的action

export const saveEditedData = data => dispatch => {
  dispatch({
    type: CHANGE_DATA,
    data,
  });
 }

and then in reducer 然后在减速器中

 case 'CHANGE_DATA': 
      return {
        ...state,
        obj: {
         ...state.obj,
         name: action.data.name,
         age: action.data.age,
       }
    }

The problem that I'm facing is that if one value is updated and another is not then after this action my second value in empty. 我面临的问题是,如果一个值被更新,而另一个值未更新,那么在执行此操作后,我的第二个值将为空。

My question is what is a good way to determine which field is changed and update only it? 我的问题是什么是确定更改哪个字段并仅对其进行更新的好方法?

So far I only came up with putting if else in action to dispatch certain thing. 到目前为止,我只是想让if else采取行动来调度某些事情。 Maybe there is a better way? 也许有更好的方法?

You can 1. make each field update with individual actions, changeName , changeAge , etc, or 2. filter the action payload to get rid of the unwanted values before putting them in your obj : 您可以1.使用单独的动作, changeNamechangeAge等使每个字段更新,或2.在将动作有效载荷放入obj之前,过滤掉动作有效载荷以除去不需要的值:

 case 'CHANGE_DATA': 
      return {
        ...state,
        obj: {
         ...state.obj,
         ...action.data.filter(el => !!el)
       }
    }

(the !! notation is converting the array elements to booleans when filtering, not strictly necessary but sanitary) !!表示法是在过滤时将数组元素转换为布尔值,并非严格必要,但很卫生)

EDIT: Sorry I misunderstood your data shape, see comments. 编辑:对不起,我误解了您的数据形状,请参阅注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM