反应-useState-更新状态:值与功能

时间:2020-07-19 10:23:12

标签: 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>
  );
}

官方文档在功能更新部分中提到了这一点: https://reactjs.org/docs/hooks-reference.html#functional-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>
    </>
  );
}

在这里,它使用了不同的方法: 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>
  );
}

我认为在上面的一个非常基本的示例中,以哪种方式都没有关系,但是在某些情况下,其中一个是必要的/比另一个更可取。

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

setCounter2(prevState => prevState + 1);

setCounter(count + 1);

我了解在一个实际示例中,在两种情况下,理想情况下都应将其(即setCounter)带到一个单独的函数中(在jsx中不内联编码)。

1 个答案:

答案 0 :(得分:1)

更新:

setCounter2(prevState => prevState + 1);

setCounter(count + 1);

有所不同,但取决于用例。您在示例中使用的方式没有区别。但是

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

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

在示例1中的

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

何时申请

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

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

您可以在here

中阅读更多内容