React - useState - 更新状态:值与函数

Was*_*and 4 reactjs use-state

我想知道在引用先前状态时传递值和传递函数来更新功能组件中的状态是否有任何区别,如下所示:

import React, { useState } from "react";

export default function App() {
  const [counter, setCounter] = useState(0);
  const [counter2, setCounter2] = useState(0);

  const increaseCounter = () => {
    setCounter(counter + 1);
  };

  const increaseCounter2 = () => {
    setCounter2(prevState => prevState + 1);
  };

  return (
    <div className="App">
      <h1>Counter: {counter}</h1>
      <button type="button" onClick={increaseCounter}>
        Increase
      </button>
      <h1>Another Counter: {counter2}</h1>
      <button type="button" onClick={increaseCounter2}>
        Increase
      </button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

官方文档在功能更新部分提到了这一点: https ://reactjs.org/docs/hooks-reference.html#function-updates

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

但在这里,它使用了不同的方法: https://reactjs.org/docs/hooks-state.html

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

我认为在上面的一个非常基本的示例中,哪种方式并不重要,但可能会出现一种情况比另一种更必要/更可取的情况。

编辑:只是为了澄清我唯一的问题是关于以下之间的区别(何时使用):

setCounter2(prevState => prevState + 1);
Run Code Online (Sandbox Code Playgroud)

setCounter(count + 1);
Run Code Online (Sandbox Code Playgroud)

我知道在这两种情况下,在真实的例子中,理想情况下它(即 setCounter)应该被带到一个单独的函数(不是在 jsx 中内联编码)。

Mon*_*mal 5

更新:

setCounter2(prevState => prevState + 1);

setCounter(count + 1);

存在差异,但取决于用例。您在示例中使用的方式没有区别。但

// Example 1
useEffect(() => {
  setCounter(count + 1)
}, [count])

// Example 2
useEffect(() => {
  setCounter2(prevState => prevState + 1)
}, [])

Run Code Online (Sandbox Code Playgroud)

在示例 1 中:useEffect 有一个依赖项要求,即 count。在示例 2 中: useEffect 没有任何依赖性要求,原因 prevState 是回调。

何时申请

  1. 如果 useEffect 仅取决于计数变化,则应应用示例 1
  2. 如果 useEffect 有其他依赖项,但您不想在计数更改时触发 useEffect,则应应用示例 2

useEffect(() => {
  if(someOtherThingsChanged) {
    setCounter2(prevState => prevState + 1)
  }
  
}, [someOtherThingsChanged])

Run Code Online (Sandbox Code Playgroud)

您可以在这里阅读更多内容