我正在一个redux项目中,我想检索存储在API服务器中的值。我想将来自API的数据存储在我的redux存储中,然后检索这些值并将其显示在我的react组件中.API中的数据服务器采用对象的形式,但是每个值都有一个唯一的ID。因此,在我的情况下,数据是帖子列表。因此,每个帖子都有一个唯一的ID,并具有所有其他详细信息,例如时间戳, title,post-author等。这是来自API的默认数据如下所示:
const defaultData = {
"8xf0y6ziyjabvozdd253nd": {
id: '8xf0y6ziyjabvozdd253nd',
timestamp: 1467166872634,
title: 'Udacity is the best place to learn React',
body: 'Everyone says so after all.',
author: 'thingtwo',
category: 'react',
voteScore: 6,
deleted: false,
commentCount: 2
},
"6ni6ok3ym7mf1p33lnez": {
id: '6ni6ok3ym7mf1p33lnez',
timestamp: 1468479767190,
title: 'Learn Redux in 10 minutes!',
body: 'Just kidding. It takes more than 10 minutes to learn technology.',
author: 'thingone',
category: 'redux',
voteScore: -5,
deleted: false,
commentCount: 0
}
}
注意:此处的“ id”是一个随机数(例如“ 8xf0y6ziyjabvozdd253nd”)变为整数,即第一个帖子获得的id为1,第二个帖子为2。
因此,我能够将来自帖子API的数据存储在我的redux“商店”中。我将posts对象转换为数组(因为我们无法映射到对象),因为我想映射到该数组并在React组件中显示数据。但是,我无法在我的数组中看到数组的结果组件,也许是因为它在数组中的每个对象之前都有一个id。这就是我试图映射到数组的方式,但没有收到任何错误,但是我没有看到component.My组件中对象的结果。看起来像这样:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import _ from 'lodash';
class PostsIndex extends Component {
componentDidMount() {
this.props.dispatch(fetchPosts())
.then(() => {
this.setState({
loading : false
});
// console.log(this.props.posts.posts[0])
})
}
render() {
// console.log(this.props.posts.posts)
const obj = this.props.posts.posts;
let arr;
if (obj) {
arr = Object.values(obj); //Converting an Object into an array
}
console.log(arr); //returns the converted array from an object
return(
<div>
{
arr ?
<div>
{ arr.map(post =>
{
<div>
{post.title}
</div>
})
}
</div>
:
<div>
No Data
</div>
}
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps)(PostsIndex);
当我console.log我的状态时,转换后的数组如下所示:
展开后的样子:
我想从上面的数组中检索几乎所有的值,谁能告诉我如何从数组中获取数据并映射到数组上以显示React组件中的值吗?
最佳答案
您忘记了地图内的return
。
render() {
const obj = this.props.posts.posts;
let arr;
if (obj) {
arr = Object.values(obj); //Converting an Object into an array
}
return (
<div>
{ arr ?
<div>
{ arr.map(post => {
return (
<div key={post.id}>
{post.title}
</div>
)
})
}
</div> :
<div>
No Data
</div>
}
</div>
);
}
或者,也可以使用oneliner将花括号放下:
arr.map(post => (<div key={post.id}>
{post.title}
</div>
)
)
并且不要忘记
key
属性。我还建议您以抽象方式使用您的哑组件。这将使您的代码更具可读性。