简体   繁体   English

React redux 正确状态更新

[英]React redux correct state update

I have a question is this code correct?我有一个问题,这段代码正确吗? State in React is inmutable so this is correct or not? React 中的状态是不可变的,所以这是正确的还是错误的?

 case "GET_SINGLE":
      const newState = [...state.data];
      const id = action.payload;
     
      const item = newState.filter((item) => item.id === id.id);
   
      return {
        ...state,
        record: item[0],
      };

Your state has a property data with an array of objects and a property record with the current object.您的状态有一个带有对象数组的属性data和带有当前对象的属性record If you are looking on opinions of the state structure, I think this is an unnecessary duplication.如果您正在查看对国家结构的意见,我认为这是不必要的重复。 You could just save the id of the current record and use a selector to get the whole object.您可以只保存当前记录的 id 并使用选择器来获取整个对象。 It's not good to have the same data in multiple places because you want a single source of truth.在多个地方拥有相同的数据并不好,因为您需要单一的事实来源。

But as far as this selector is concerned, you are finding the item which matches the id from the action.payload and saving it the the property record .但是就这个选择器而言,您正在查找与action.payload中的id匹配的项目,并将其保存在属性record You are only looking for one item so you should use find() instead of filter() .您只是在寻找一项,因此您应该使用find()而不是filter()

Using the variable id.id is very confusing.使用变量id.id非常令人困惑。 You can use destructuring to get just the id from the payload ( const {id} = action.payload; ).您可以使用解构从有效负载中获取id ( const {id} = action.payload; )。 Or you could just use action.payload.id in your comparison ( item.id === action.playload.id ).或者你可以在你的比较中使用action.payload.id ( item.id === action.playload.id )。

 case "GET_SINGLE":
      const {id} = action.payload;
     
      const item = state.data.find((item) => item.id === id);
   
      return {
        ...state,
        record: item,
      };

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

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