簡體   English   中英

react異步更新state hook

[英]Asynchronously update state hook in react

我試圖在異步 function 中設置由useState生成的 state,但我發現如果我這樣做,React 會無限渲染我的組件。

這是我做的demo

export const App = () => {
    const [nodes, setNodes] = useState([])

    // some async refresh code, like http request, like axios.get("/list-nodes").then ...
    const refresh = async () => {
        let arr = []
        for (let i = 0; i < 10; i++) {
            arr.push(Math.random())
        }
        setNodes(arr)
    }

    refresh();


    return (
        <div>
            {
                nodes.map(v =>
                    <div>
                        value: {v}
                    </div>)
            }
        </div>
    )
}

在代碼中,渲染在不斷發生,數字也在不斷變化。

請問我如何能夠在異步 function 中正確設置 state?

您需要使用 useEffect 掛鈎來僅在第一次渲染時獲取數據。 如果不是,組件在每次渲染時獲取,每次更新 state 時都會發生,這會渲染組件...

export const App = () => {
    const [nodes, setNodes] = useState([]);

    useEffect(()=>{
      //Self calling async function
      //Be carefull to add a ; at the end of the last line
      (async () => {
        let data = await fetch(url)
        let json = await data.json()
        setNodes(data)
      })()
    },[])

    return (
      <div>
      {  nodes.map(node => <div>Value: {node}</div>)  }
      </div>
    )
}

你可以使用 useEffect

 export default function App() {
  const [nodes, setNodes] = useState([]);
  const refresh = async () => {
  let arr = [];
   for (let i = 0; i < 10; i++) {
     arr.push(Math.random());
   }
   setNodes(arr);
 };
useEffect(() => {refresh(); }, []);

return (
<div className="App">
  {nodes.map((v) => (
    <div>value: {v}</div>
  ))}
 </div>
);}

暫無
暫無

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

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