簡體   English   中英

React hooks - useState()不會使用新的狀態更新重新呈現UI

[英]React hooks - useState() is not re-rendering the UI with the new state updates

我正在嘗試新的React Hooks,我有點卡住,因為當本地狀態更新時UI沒有更新。 這是我的代碼,

 import React, { useState, useEffect } from 'react'; import Post from './Post' import PostForm from './PostForm'; import axios from 'axios'; function PostsList() { const [posts, setPosts] = useState([]); // setting up the local state using useEffect as an alternative to CDM useEffect(() => { axios.get('...') .then(res => { // the resposne is an array of objects setPosts(res.data) }) }) const handleSubmit = (data) => { // the data I am getting here is an object with an identical format to the objects in the posts array axios.post('...', data) .then(res => { // logging the data to validate its format. works fine so far.. console.log(res.data); // the issue is down here setPosts([ ...posts, res.data ]) }) .catch(err => console.log(err)) } return ( <div> <PostForm handleSubmit={handleSubmit} /> <h3>current posts</h3> { posts.map(post => ( <Post key={post.id} post={post} /> )) } </div> ) } 

當我提交表單時,UI會瞬間閃爍,然后在沒有新更新的情況下呈現當前狀態,似乎有些事情阻止它重新呈現新狀態。 如果需要更多代碼/說明,請在下面留言。 提前致謝。

好吧,問題通過@skyboyer的有用提示解決了,
所以最初發生的事情是, useEffect()就像componentDidMount()componentDidUpdate() ,這意味着無論何時狀態更新,都會調用useEffect() ,這意味着重置初始狀態來自服務器的數據。 修復我需要使用的問題useEffect()在創建/渲染時只渲染組件一次,而不是每次對狀態進行更新時渲染它。 這是通過將一個空數組作為第二個參數添加到useEffect()函數來完成的。 如下所示。

  useEffect(() => { axios.get('...') .then(res => { setPosts(res.data) }) }, []) 
謝謝 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM