函数组件内的 React 非状态变量不会立即更新

React non state variables inside function component are not updated instantly

我知道react的useState钩子是异步的所以如果我用useState存储变量并在上面调用set函数,它可能不会立即更新。

但是现在我使用简单的变量来存储值,但变量值仍然没有更新。我该如何解决?

const List=(props)=>{
    let count = 1;
    const onNextButtonClick = ()=>{
        count  = count +1;
        console.log(count );
        updatePage();
    }
    return (
        //html
    )
}

我发现只要单击下一个按钮,c 的值就不会增加,而我在控制台上得到的 c 值相同。

为什么会这样?

count 需要存储在状态中,并且因为状态更新可能会被分组并异步处理,所以在 useEffect 派上用场的下一次渲染之前你不会看到变化.

const { useEffect, useState } = React;

function Example() {

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

  function onNextButtonClick() {
    setCount(count + 1);
    // the other thing
  }

  useEffect(() => {
    if (count) console.log(count);
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={onNextButtonClick}>
        Click me
      </button>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>