3 回答

TA贡献1765条经验 获得超5个赞
class Post extends Component {
state = {
postsList: [],
};
componentDidMount() {
// const postId = this.props.match.params.id
// fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`)
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => this.setState({
postsList: [...data],
}));
};
renderList = () => this.state.postsList.map((item, id) => <div>>{item.title}></div>);
render() { return (
this.renderList()
);
}
}
postList应该是一个Array。您可以使用扩展运算符来强制执行此操作(但无论如何,索引看起来都包含一个数组)。我还更改了 fetch 以检索/posts索引而不是/posts/:id 这里的主要区别是/posts返回一个post对象数组

TA贡献1770条经验 获得超3个赞
这里有两个问题。PostLists被声明为Object初始。将其声明为空array
state = { postlists : [] }
render return语句不正确,您正在返回一个包含在jsx分隔符中的函数。将内部语句包装在Fragments和{ }
render(){
return(
<>
{ this.renderList() }
</>
)
}
或者只是删除分隔符
render(){
return this.renderList()
}
如果 API 调用返回一个Object而不是数组,您应该将声明保留为空对象并映射它的条目
renderList = () => Object.keys(this.state.postsList).map((key, id) => <div>>{this.state.postsList[key].title}></div>)

TA贡献1811条经验 获得超5个赞
此外,最初它是一个对象而不是数组
class Post extends Component {
state = {
postsList: [] // update here
};
componentDidMount() {
// const postId = this.props.match.params.id
// fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`)
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => this.setState({
postsList: Array.isArray(data) ? data : [data], //just to wrap if it is a sinle object
}));
};
renderList = () => this.state.postsList.map((item, id) => <div>>{item.title}></div>);
render() { return (
this.renderList()
);
}
}
export default Post;
这就是你得到的回应。
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
只有数组有 .map 方法,这里它返回一个单一的对象,你不能映射它
添加回答
举报