我在构建应用程序时出错js:1375警告:列表中的每个子项都应该有一个唯一的"key"道具。在应用程序中(位于src/index.js:7(这是来自api的响应,我也有这个问题,我不能正确地将数组呈现为列表
(15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
这是我的代码
import React, { Component } from 'react'
import ImagesSearch from './ImagesSearch'
import axios from 'axios'
export class Images extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
searchquery: '',
};
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onChange(e) {
this.setState({searchquery:e.target.value})
}
onSubmit(e) {
e.preventDefault()
this.images(this.state.searchquery)
console.log(this.state.searchquery)
}
images(query) {
return axios.get(`https://api.pexels.com/v1/search?
query=${query}+query&per_page=15&page=1`, {
headers: { Authorization: `` }
}).then(res => {
console.log(res.data.photos)
this.setState(prevState => ({
data: [res.data.photos]
}))
console.log(this.state.data)
return res.data
}).catch(err => {
console.log(err)
})
}
render() {
const mapRows = this.state.data.map((item) => (
<div key={item.id}>
<li>
<span>Name : {item.url}</span>
<span>User Type: {item.url}</span>
</li>
</div>))
return (
<div>
<form class="form-group m-2" onSubmit={this.onSubmit}>
<label>Search</label>
<input class="form-control form-control-sm w-25 mx-auto" name="searchquery" type="text" placeholder="Search" onChange={this.onChange} />
<button type="submit" class="btn btn-primary mt-2">Submit</button>
</form>
<div>
{ mapRows }
<div>
</div>
)
}
}
export default Images
谢谢你的帮助
您的setState
阶段与[res.data.photos]
错误。res.data.photos
是数组值,但您也将其再次设置为数组。因此,状态值将是这样的:
data: [[{...}, {...}, ..., {...}]]
您应该使用res.data.photos
而不是[res.data.photos]
。
images(query) {
...
this.setState(prevState => ({
data: res.data.photos // your code was [res.data.photos]
}))
...
}
此外,如果id重复,则可以使用index
而不是id
。尝试使用以下方法以避免Warning
。
const mapRows = this.state.data.map((item, index) => (
<div key={index}>
<li>
<span>Name : {item.url}</span>
<span>User Type: {item.url}</span>
</li>
</div>
));
听起来您的数组有重复的id值,或者数组中的对象缺少id属性。
const mapRows = this.state.data.map((item) => (
<div key={item.id}> // possible duplicate here
<li>
<span>Name : {item.url}</span>
<span>User Type: {item.url}</span>
</li>
</div>))