[英]Array becoming object when stored in state in react
我正在從我的 api 獲取一些數據。 在獲取數據的回調中,數據是一個數組:
const classes = useStyles();
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://forum-temp.herokuapp.com/api/posts')
.then((res) => res.json())
.then((res) => {
console.log(typeof res.data.docs) // Array
setPosts(res.data.docs);
});
}, []);
在我的功能組件的 return 語句中 -
<div className="post__container">
{ {posts.map((post, i) => (
<MiniPost
dp="https://picsum.photos/200"
username="blah"
time="blah"
heading="blah"
comments="4"
history={history}
key={i}
/>
))} }
</div>
那是因為你是雙重包裝。 React 僅使用單包裝。 僅使用一組{}
像這樣{posts.map( ... )}
:
<div className="post__container">
{posts.map((post, i) => (
<MiniPost
dp="https://picsum.photos/200"
username="blah"
time="blah"
heading="blah"
comments="4"
history={history}
key={i}
/>
))}
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.