在Redux中映射对象数组数据

时间:2016-04-29 03:32:04

标签: javascript object reactjs mapping redux

我使用axios和redux作为api请求,返回一个response.data,它是一个对象数组。

我的动作减速器如下:

export default function(state = [], action) {
  switch (action.type) {
     case FETCH_USERS:
         console.log(action.payload.data)
         return { ...state, users: action.payload.data };
       }
  return state;
}

console.log在chrome控制台中返回

 [object, object]

我的问题出现在如何映射对象的数据上。我尝试了以下我映射数组的地方。 (用户是对象数组的支柱。)

  ....
 {this.props.users.map(this.renderUser)}
 ...

 renderUser(user) {
  return (
    <tr>
      <td> {user.contact_name}</td>
      <td> {user.contact_email}</td>
    </tr>
  );
}

当我使用React控制台检查我的道具时,我得到以下内容:

users: {...}
   users: 
      0:{...}
      1:{...}

我不确定如何将对象映射到html。如果我将它转换为字符串并映射它会更好吗?我的映射显示为空白。

2 个答案:

答案 0 :(得分:3)

您的问题是您的州名与您的阵列同名,这让您感到困惑。

您的用户缩减器是

AVCaptureVideoDataOutputSampleBufferDelegate

当您使用名称“users”将其映射到道具时,您获得的是

const initialState = {
   ....
   users : []
}

因此,为了访问您需要使用的用户

this.props.users = initialState

也就是说,访问用户的方式就是这样。

this.props.users.users

答案 1 :(得分:1)

pd.DataFrame(df[0].apply(list).values.tolist()) Out[846]: 0 1 2 3 4 5 6 7 8 9 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 1 1 0 0 0 2 0 0 1 1 0 1 1 0 0 0 3 0 0 1 1 0 1 1 0 1 0 4 1 0 1 1 0 1 1 0 0 0 5 1 0 1 1 0 1 1 0 0 0 6 0 0 1 1 0 1 1 0 0 0 7 1 0 1 1 0 1 1 0 0 0 8 0 1 0 0 1 0 0 1 0 1 9 1 0 1 1 0 1 1 0 0 0 中,如果您的store是嵌套对象,则可以在users中修复此问题。
它不仅告诉react / redux 您想要哪些数据,还要确认 如何根据存储在redux mapStateToProps中的方式转换/映射所述数据 如何让它出现在store上:

props

现在,在您的组件中,您可以访问mapStateToProps( store ){ return { users: store.users.users, } } (数组)并将其映射为users,而不是this.props.users.users。

您可以看到的另一件事是如何从API中提取数据并将其存储到redux this.props.users中。
如果您的API为您提供了嵌套数据(我正在使用的API上的一个路由,奇怪的是这样做了)。

在那种情况下...... 为了使您的道具/州/商店对象具有预期的格式,请更改以下行:

store

到此:

return { ...state, users: action.payload.data };

完整功能如下所示:

return { ...state, users: action.payload.data.users };