Redux状态下如何保持秩序?

R. *_*sch 3 arrays json state reactjs redux

我读到,不建议在 Redux 中使用数组作为状态对象。所以人们不应该有,state = [ {}, {}, {} ]而是应该有state={ "id1": {}, "id2": {}, "id3": {} }

我有一个返回用户数组的 API 端点。我主要想按照每个用户在数组中出现的顺序准确显示它。

In a use case like this, is it still not advisable to save this as an array in state? The problem seems to be that I will need to show the users in the particular order, but I do also sometimes need to access users by id, so I am confused what a common strategy would be here to (1) keep the order and (2) access each object in a fast and efficient way (by id)?

edit: I am using mongodb id's for each user object, so id's and order does not simply match up. So it's not like object no. 1 (in terms of order) also has id 1. (although I could of course ignore mongos id's and implement my own, if that's good practice)

Cha*_*man 5

我的团队使用的策略是让状态看起来像这样

const state = {
  byID: {
    id: Object
  },
  ids: ["1", "2"...] // array of ids 
}
Run Code Online (Sandbox Code Playgroud)

为了显示数据,我们有一个列表组件,它订阅 ids 数组并迭代它们。然后,我们有了为 id 数组中的每个项目渲染的单个项目组件,它接受 id 作为列表中的 prop,并且它还订阅该byID对象。然后,它使用传入的 id 从byID要渲染的对象中检索确切的项目。

这样,顺序将保持不变,同时仍然为您提供将状态存储在对象中而不是数组中的所有好处。

单项组件的示例。

class Person extends React.Component {
  render() {
    return (
      <div>
        <span>{this.props.person.firstName}</span>
      </div>
    );
  }
}

function mapStateToProps(state, ownProps) {
  return {
    person: state.people.byID[ownProps.id]
  }
}
Run Code Online (Sandbox Code Playgroud)