I'm trying to fetch data from this api https://randomuser.me/api/?results=25 with this code
function Users() {
const [Users, setUsers] = useState([])
useEffect(() => {
axios.get('https://randomuser.me/api/?results=25')
.then(Response=>{
if(Response.data){
alert("FOund")
setUsers([Response.data])
}else{
alert("not found")
}
})
}, [])
const displaylist = Users.map((User,index)=>{
return(
<h3>{User.gender}</h3>
)
})
return (
<div>
{displaylist}
</div>
)
}
export default Users
But nothing is showing up and console is giving this error: Warning: Each child in a list should have a unique "key" prop.
Check the render method of Users
. See https://reactjs.org/link/warning-keys for more information. at h3 at Users (http://localhost:3000/static/js/main.chunk.js:627:83) at div at App
When you map through an array React needs a unique key, something like a User.id; in this case you could use the index as well. I changed your function a little bit like this:
function Users() {
const [Users, setUsers] = useState([]);
useEffect(() => {
axios.get("https://randomuser.me/api/?results=25").then((Response) => {
if (Response.data) {
alert("FOund");
setUsers(Response.data.results);
} else {
alert("not found");
}
}).catch(error => console.log(error));
}, []);
const displaylist = Users.map((User, index) => {
return <h3 key={index}>{User.gender}</h3>;
});
return <div>{displaylist}</div>;
}
export default Users;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.