【发布时间】:2020-04-10 00:28:32
【问题描述】:
我正在尝试从 rest api 获取数据,然后在我的浏览器上将其呈现为文本。但是,我不断收到以下错误:index.js:1 Warning: Each child in a list should have a unique "key" prop. 我的密钥道具列在下面。有人能告诉我我做错了什么吗?我在下面列出了我的关键道具,认为它会在渲染中以这种方式工作(我将它用于另一个项目中的另一个 api 调用并且它有效)。
这就是在 api 中设置笑话的方式。
{
"id": "R7UfaahVfFd",
"joke": "My dog used to chase people on a bike a lot. It got so bad I had to take his bike away.",
"status": 200
}
这是我获取它的代码。
import React, { Component } from 'react';
class JokesApi extends Component {
constructor(props){
super(props);
this.state = {
jokes: [],
};
}
componentDidMount(){
fetch('https://cors-anywhere.herokuapp.com/https://icanhazdadjoke.com/', {
headers: {
'Content-Type': 'appliction/json',
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(data => this.setState(prev => ({jokes: prev.jokes.concat(data.joke)})))
}
render () {
var jokes;
return (
<ul>
{this.state.jokes.map(joke =>
<div key={joke.id}>
<p>{jokes}</p>
</div>
)}
</ul>
)
}
}
export default JokesApi;
【问题讨论】: