[英]array.map is not a function, reactjs setState error
After setting the state reactJs comes up with an error blogs.map is not a function.设置 state reactJs 后出现错误 blogs.map 不是 ZC1C425268E68385D1AB5074。 How do I convert blogs into arrays, although it is initialized as an array.
如何将博客转换为 arrays,尽管它已初始化为数组。
const [blogs,setBlogs] = useState([]);
useEffect(async() => {
await axios.get(`${API_URL}/api/getblogs`,{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
.then((res)=>{
res.data.result.forEach(element => {
element.blogArray.forEach((b)=>{
// console.log(b);
setBlogs(b);
})
});
})
.catch((err)=>{
console.log(err)
})
}, []);
useEffect(()=>{
console.log(blogs)
},[blogs]);
return(
<div className="row">
{
blogs &&
blogs.map((blog)=>{
return (
<Cardschema key={Math.random()}/>
)
})
}
</div>
)
You should not call setBlogs
method multiple times.您不应该多次调用
setBlogs
方法。 Instead aggregate all the data and set it once而是聚合所有数据并设置一次
.then((res)=>{
var blogs = []
res.data.result.forEach(element => {
element.blogArray.forEach((b)=>{
// console.log(b);
blogs.push(b);
});
});
setBlogs(blogs);
});
Since blogArray already is an array you should be able to do:由于 blogArray 已经是一个数组,你应该能够做到:
setBlogs([...blogs, ...blogArray])
and skip at least the second loop.并至少跳过第二个循环。
Now I can imagine you might want to modify the data before setting it to state in that case I would recommend not using forEach like your code but map (at least for the nested loop).现在我可以想象你可能想在将数据设置为 state 之前修改数据,在这种情况下,我建议不要像你的代码那样使用 forEach,而是使用 map(至少对于嵌套循环)。 Which would look like this.
看起来像这样。
const formattedBlogrray = element.blogArray.map((blog)=> {
// do formatting
return {
...formattedBlog,
}
});
setBlogs([...blogs, ...formattedBlogArray])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.