简体   繁体   中英

How to set redux initial state for array of objects?

I am using redux for my react app. I am fetching user data from api, updating redux state with it and showing it into my component. The data is list of objects. The thing what causes me problem is setting redux initial state.

Reducer initial state:

const initState = {
    users: []
}

Reducer action

case 'GET_USERS':
    return {
        users: action.users
    }
});

Render in component

{this.props.users[1].name}

On first rendering i am getting error can't read from undefined property. That is cause on first rendering data isn't stored yet and that object with that property doesn't exist yet. I can solve that if i set initial state like:

const initState = {
    users: [
        {name: "", age: ""},
        {name: "", age: ""}
    ]
}

In that case object with property would exist and i wouldn't get error. But i don't know how many objects i will have and i don't want to set initial state for every of them and theirs properties. So what is the way to properly set it?

只需检查它是否存在并有条件地渲染

{this.props.users.length > 1 ? this.props.users[1].name : 'Not enough elements!'}

You shouldn't render a user by its position like that. Either you iterate all users or look into normalizing your data

<div>
  {users.map(user) => (
    <div>{users.name}</div>
  )}
</div>

https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape

我将使用一个空数组,并在渲染前检查[] .length属性。

You mention your object structure

{name: "", age: ""}

and then you mention how to access users.name.firstname . If you get an undefined that means your dara hasn't loaded into your users array. So, instantiate with an empty array such as users:[] and add the following:

const YourComponent = (props) => {
  if (users.length === 0){
    return <div> Loading </div>
  }
  return(
    <div>
      {users.map(user => 
        <div>
          {user.name}
        </div>  
      )}
    </div>
  )
}

Your component will load before your array will be populated and will return the Loading div. When the array will be filled, the component will rerender and will map out your array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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