3 回答

TA貢獻1886條經驗 獲得超2個贊
您的代碼是正確的,但狀態并未立即放置,因此當您調用控制臺日志時,該值尚未準備好,但如果您在 html 中顯示該數據,則這不會成為問題
對您的代碼進行了一些更改和少量組織
export default Test = {
const [ posts, setposts] = useState([]);
useEffect(()=>{
fetch('https://jsonplaceholder.typicode.com/posts')
.then(result => result.json())
.then((data)=>{
console.log(data); // Will be written because you are already at the end of the promisse
setposts(data);
console.log(posts); // Will be empty cuz the async load of state
});
},[])
return (
<>
{posts.map(post => (
<ul>
<li key="{post.id}">{post.title}</li>
</ul>
))}
</>
)
}

TA貢獻1798條經驗 獲得超3個贊
基本上,react 不會立即更改狀態,
如果您想看到狀態確實發生了變化,請嘗試渲染帖子,例如(我知道,這是一個糟糕的例子):
... return?( ????????<div>{JSON.stringify(posts)}</div> ????)

TA貢獻1797條經驗 獲得超6個贊
useState API 沒有像 React 類中的 setState 那樣的回調。為了等待狀態更新完成,您所能做的就是使用 useEffect 掛鉤,如下所示
useEffect(()=>{
fetch('https://jsonplaceholder.typicode.com/posts',{
method:'get',
}).then(result=>{
return result.json();
}).then((data)=>{
console.log(data);
setposts(data);
console.log(posts);
})
},[data])
添加回答
舉報