在react / redux中从reducers返回一个新状态的最佳做法是什么?

时间:2018-05-18 07:00:19

标签: reactjs redux

从reducer返回新状态的最佳做法是什么?是使用$set中的updateimmutability-helpers,还是使用Object.assign()

3 个答案:

答案 0 :(得分:2)

我个人在处理易于管理状态的项目时不会使用不变性助手。如果你有一个非常大的状态,那么使用不变性助手会很有帮助,这样你就不会犯错误。

为了在reducer中返回状态,通常使用spread运算符返回新状态。这看起来像这样:

return {...state, newProp: 'value', etc...}

答案 1 :(得分:0)

你可以在redux中的reducer中创建新状态,也可以使用set方法改变状态,你可以作为props返回索引页面

ex:在reducer中你写如下

return state.set(' tasks',action.response)

答案 2 :(得分:0)

首先,您应该清楚地了解redux。它是你前端的后门店。 redux将数据存储为您定义的堆叠技术FIFO或LIFO。
你不能重新分配,只需使用ES6 SPREAD运算符并使用解构返回action-object。我试着在下面给出一个例子:

const postsReducerDefaultState = [];
const postsReducer = (state=postsReducerDefaultState, action) => {
switch(action.type) {
  case 'ADD_POST':
    return [action.post, ...state];
  case 'REMOVE_POST':
    return state.filter(post => post.id !== action.id)
  case 'SET_POSTS':
    return action.posts;
  default:
    return state;
  }
};
export default postsReducer;

ADD_POST:首先返回[action.post, ...state],然后传播旧帖子。
SET_POSTS:返回action.posts您已经通过的行动。
如果要设置对象属性,请使用解构

return {
      ...state,
      text:action.text
    }

text财产已经在您的州。如果没有,那么它会为你的州增加一个属性。我认为它可以帮助你理解redux。