使用Redux和ReactJS以对象和数组格式获取API Json数据

时间:2018-11-24 12:04:14

标签: reactjs redux

在Redux的以下教程中,我成功地从示例代码中获取了数据。

https://codepen.io/stowball/post/a-dummy-s-guide-to-redux-and-thunk-in-react

下面是该教程中使用的格式,效果很好。

newCell *cell = (newCell *)[self.myTableView dequeueReusableCellWithIdentifier:@"newCell" forIndexPath:indexPath];

但是我尝试了几种方法,但无法通过以下格式传递数据

[
    {
        "id": 1,
        "label": "List item 1"
    },
    {
        "id": 2,
        "label": "List item 2"
    },
    {
        "id": 3,
        "label": "List item 3"
    },
    {
        "id": "4",
        "label": "label 4"
    },
    {
        "id": "5",
        "label": "label 5"
    }
]

另一个文件中的Current Reducer和映射组件:

{     
    "banner": [ 
        { "key": "product", "id": "84535", "image_url": "/media/emthemes/slideshow/s/u/sultry-app_12.jpg" }, 
        { "key": "category", "id": "2629", "image_url": "/media/emthemes/slideshow/l/i/limecrime-app.jpg" }, 
        { "key": "product", "id": "84654", "image_url": "/media/emthemes/slideshow/a/m/ameera-app-banner.jpg" } 
    ] 
}

尝试对reducer进行以下更改:

export function items(state = [], action) {
    switch (action.type) {
        case 'ITEMS_FETCH_DATA_SUCCESS':
            return action.items;

        default:
            return state;
    }
}

return (
            <ul>
            {this.props.items.map((item) => (
              <li key={item.id}>
                {item.id}
              </li>
            ))}
            </ul>
        );

1 个答案:

答案 0 :(得分:0)

将减速器更改为此:

{this.props.items.banner.map((item) => (
              <li key={item.id}>
                {item.id}
                {item.key}
                {item.image_url}
              </li>
            ))}

并在ItemList.js中更改项目的PropTypes

items: PropTypes.object.isRequired

我尝试了本教程,并在此处创建了一个有效的示例: https://github.com/stackOverflow166/redux-nwb

Edit2:

无法读取属性“地图”

这是关于日期类型的问题。将其添加到ItemList.js以将日期类型更改为array。只有array具有map函数。

let bannerArray = []
let banner = this.props.items.banner
for (let key in banner){
     bannerArray.push(banner[key])
}