![](/img/trans.png)
[英]Why can't useEffect access my state variable in a return statement?
[英]React : i can't access to my state from my useEffect
在我的反應函數的返回中,我想做一個 response.data.map(...),但我不能,“響應”是未定義的,因為它在我的 useEffect(范圍問題)中。
所以我嘗試使用 useState 創建一個包含 response.data 的狀態,但問題是我的 console.log 總是返回 undefined,這是我狀態的默認狀態。
所以我嘗試使用 prevstate ,因為我認為問題是考慮了以前的狀態,但顯然語法不好。 :
const Comments = ({ postId }) => {
// States
const [allComments, setAllComments] = useState()
useEffect(() => {
async function fetchData() {
const data = {
postId: postId,
};
const response = await POST(ENDPOINTS.GET_ALL_COMMENTS, data);
if (response.data[0]) {
setAllComments((prevState) => ({
...prevState,
response.data
}))
} else {
}
}
fetchData();
console.log(allComments)
}, []);
return (
<div>
{allComments.map(...)}
</div>
);
};
我終於嘗試這樣做:
setAllComments ((prevState) => ({
... prevState,
response
}))
這次語法很好,但是我的來自 allComments 的 console.log 仍然未定義......
如何從我的退貨中訪問我的 response.data? 我們應該使用useState、prevstate還是其他?
您不能在對象 ( {}
) 上使用.map()
)。
如果您的注釋是一個數組,則需要使用數組展開運算符 ( [..., ...]
):
const Comments = ({ postId }) => {
const [allComments, setAllComments] = useState([]);
useEffect(() => {
async function fetchData() {
const response = await POST(ENDPOINTS.GET_ALL_COMMENTS, {
postId,
});
const data = response.data;
if (Array.isArray(data)) {
setAllComments((prevState) => [...prevState, ...data]);
} else {
throw new Error("Oops, didn't get an array.");
}
}
fetchData();
}, [postId]);
return <div>{JSON.stringify(allComments)}</div>;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.