亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么函數 useState 不更新值?

為什么函數 useState 不更新值?

長風秋雁 2023-09-07 16:19:18
我正在嘗試 React.js 但我想要的不起作用。這是我的代碼:import React, { useState } from 'react';   function App() {    const [count, setCount] = useState(0);     setCount(count + 1);    return (      <div>        <p>value of count : {count} fois</p>      </div>    );  }export default App;我有 :Too many re-renders. React limits the number of renders to prevent an infinite loop.您可以在那里看到錯誤:https://codesandbox.io/s/nostalgic-engelbart-tzbxv ?file=/src/App.js:0-244感謝您的幫助 !
查看完整描述

4 回答

?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

每當您更改狀態時,就會觸發重新渲染。


在你的情況下,當你調用setCount并且count狀態count正在改變并且它正在觸發重新渲染并且這個循環繼續時。這就是這個錯誤的原因。


嘗試這個示例,其中setCount僅調用一次并且值按預期更改。



import React, { useState, useEffect } from "react";

function App() {

? const [count, setCount] = useState(0);

? useEffect(() => {

? ? setCount(count + 1);

? }, []);

? return (

? ? <div>

? ? ? <p>value of count : {count} fois</p>

? ? </div>

? );

}


export default App;


這是另一個示例,count每次按下按鈕時 都會增加:


import React, { useState, useEffect } from "react";

function App() {

? const [count, setCount] = useState(0);

? useEffect(() => {

? ? setCount(count + 1);

? }, []);

? return (

? ? <div>

? ? ? <p>value of count : {count} fois</p>

? ? ? <button

? ? ? ? onClick={() => {

? ? ? ? ? setCount(count + 1);

? ? ? ? }}

? ? ? >

? ? ? ? Increase

? ? ? </button>

? ? </div>

? );

}


export default App;


查看完整回答
反對 回復 2023-09-07
?
呼如林

TA貢獻1798條經驗 獲得超3個贊

你正在創建一個無限循環。每次狀態更新時,組件都會重新渲染。組件正在渲染,然后調用setCount狀態更新,然后組件渲染,如此循環下去。

您可以useEffect在第一次渲染后更新狀態。

useEffect(() => {
  setCount(count + 1)
},[])

我不確定這有什么意義,因為你可以將初始值傳遞給useState


查看完整回答
反對 回復 2023-09-07
?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

您收到錯誤的原因是調用setCount(count + 1);將永遠增加狀態計數。嘗試將其放在一個條件上,例如在下面的codesandbox /代碼中,每次單擊按鈕時狀態計數都會增加1。if (count < 10)您還可以在某種條件下setInterval或在多種條件下增加 state 。只是不是無限!;)

import React, { useState } from "react";

import "./styles.css";


export default function App() {

  const [count, setCount] = useState(0);


  const increaseCount = () => {

    setCount(count + 1);

  };


  return (

    <div>

      <p>value of count : {count} fois</p>

      <button onClick={increaseCount}>start count</button>

    </div>

  );

}


查看完整回答
反對 回復 2023-09-07
?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

您正在調用setCount組件的主體,如果考慮基于類的組件,則本質上是渲染函數。因此,它會導致設置新值、重新渲染、設置新值、重新渲染等等的無限循環。

setCount您應該只從某種事件中調用,例如按鈕單擊或效果,例如使用useEffect


查看完整回答
反對 回復 2023-09-07
  • 4 回答
  • 0 關注
  • 287 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號