【问题标题】:Redux reducer - a single state object or multiple states?Redux reducer - 单个状态对象还是多个状态?
【发布时间】:2020-10-13 05:53:58
【问题描述】:

考虑reducer状态的这两种模式:

  1. 单个状态对象:
// personReducer.js
const initialState = {
  personInfo: {
    firstName: "",
    lastName: "",
    foo: "",
    bar: "",
    baz: "",
    foo1: "",
    bar1: "",
    bar2: "",
    foo2: "",
    foo3: "",
  }
  // some not-to-mention states
};
  1. 多个状态(没有person 级别):
// personReducer.js
const initialState = {
  firstName: "", // no person level
  lastName: "",
  foo: "",
  bar: "",
  baz: "",
  foo1: "",
  bar1: "",
  bar2: "",
  foo2: "",
  foo3: ""
};

哪个更好?让我困惑的是:

// Person.jsx - pattern 1
const mapStateToProps = ({ personInfo }) => {
 personInfo
}

// Person.jsx - pattern 2
const mapStateToProps = ({ firstName, lastName }) => {
 firstName,
 lastName
}

// Human.jsx - pattern 1
const mapStateToProps = ({ personInfo }) => {
 personInfo
}

// Human.jsx - pattern 2
const mapStateToProps = ({ foo, bar }) => {
 foo,
 bar
}

假设我们的应用中有两个组件PersonHuman,它们都将连接到personReducer 以检索个人信息。

对于模式 1:

Person 组件中,我调度了一个动作来更新personInfo 内部的firstName,这稍后将强制Human 也重新渲染,是吗?在我们的减速器中是这样的:

case UPDATE_PERSON_INFO: {
 return {
  ...state,
  personInfo: {
    ...state.personInfo,
    firstName: payload.firstName
  }
 }
}

对于模式 2:

Person 组件中,我调度了一个动作来更新firstName,这以后不会强制Human 重新渲染,因为Human 不是将firstName 映射到它的props,而是foo, bar .我对吗?某物 喜欢:

case UPDATE_PERSON_INFO: {
 return {
  ...state,
  firstName: payload.firstName  
 }
}

【问题讨论】:

  • 你可以有一个 personInfo reducer 并使用 combineReducers 进行 mapState 我建议使用 reselect 和撰写 selectPersonInfo,here 是一些如何使用 reselect 和 react-redux 的示例。

标签: reactjs redux


【解决方案1】:

在这两种情况下都会重新渲染,因为在这两种模式中,您都会更新对新不可变状态对象的引用。

如果您想防止不必要的组件渲染,您必须在mapStateToProps 中使用记忆选择器。这是documentation linkGitHub

这些选择器应该特定于您的组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2023-03-23
    • 2019-07-28
    • 1970-01-01
    • 2020-11-10
    • 2019-02-25
    相关资源
    最近更新 更多