簡體   English   中英

React function 未更新為 state

[英]React function doesn't updated with state

我正在嘗試執行一個使用 react state 的 function,但是當 state 更改時,function 不會更新為 state 值。

    const {useState, useEffect} = React;

function Example() {
  const [count, setCount] = useState(0);
  
  const testFunction = function(){
        setInterval(() => {
        console.log(count)
    }, 3000)
  }
  useEffect(() => {
let fncs = [testFunction];

fncs.forEach(fnc => fnc.apply(this));
  }, [])
  


  // Similar to componentDidMount and componentDidUpdate:  
  useEffect(() => {   
    // Update the document title using the browser API    
    document.getElementById('other-div').innerHTML = `You clicked ${count} times`;  
  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

ReactDOM.render( <Example />, document.getElementById('root') );

例子:https://jsfiddle.net/bzyxqkwt/4/

只是想讓你明白,我將函數傳遞給另一個組件,然后他在像這樣的某個事件上執行這些函數

fncs.forEach(fnc => fnc.apply(this, someEventParams));

我只是猜測 setInterval 僅用於演示目的,需要停止/刪除,但基本上 useEffect 捕獲初始 state。因此,如果你想在內部 function 中捕獲更新的 state,那么你應該傳遞所有值您需要(在本例中為計數參數)。 就像是:

const testFunction = function(){
    // setInterval(() => {
        console.log(count); // it should log the updated value
    // }, 3000)
  }
  useEffect(() => {
     let fncs = [testFunction];

      fncs.forEach(fnc => fnc.apply(this));
  }, [count]);   // <-- this makes the trick

暫無
暫無

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

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