简体   繁体   English

React 中 new useState 中的 prevState 是如何工作的? 它如何存储之前的 state 的值?

[英]How does prevState in new useState in React work ?? How does it store the value of previous state?

I know how to use prevState in new State, I want to know how does it actually works??我知道如何在新的 State 中使用 prevState,我想知道它实际上是如何工作的? How does this functionality works??这个功能是如何工作的? why on putting in 'prevValue' in 'setFullName' function changes its value?为什么在 'setFullName' function 中放入 'prevValue' 会改变它的值?

import React, { useState } from "react";

function App() {
  const [fullName, setFullName] = useState({
    firstName: "",
    lastName: ""
  });

  function handleChange(event) {
    let value = event.target.value;
    let name = event.target.name;

    setFullName((prevValue) => {
      if (name === "fName") {
        return {
          firstName: value,
          lastName: prevValue.lastName
        };
      } else if (name === "lName") {
        return {
          firstName: prevValue.firstName,
          lastName: value
        };
      }
    });
  }

  return (
    <div className="container">
      <h1>
        {fullName.firstName} {fullName.lastName}
      </h1>
      <form>
        <input onChange={handleChange} name="fName" placeholder="First Name" />
        <input onChange={handleChange} name="lName" placeholder="Last Name" />
        <button>Submit</button>
      </form>
    </div>
  );
}

export default App;

When a component is created (with React.createElement , or with JSX like <App /> ), React will see how many times useState is called in the component body, and will create an internal mapping of state indicies to state values.当一个组件被创建(使用React.createElement ,或使用 JSX 像<App /> )时,React 将查看在组件主体中调用了多少次useState ,并将创建 state 索引到 state 值的内部映射。 For example, with the following component:例如,使用以下组件:

const Comp = () => {
  const [v1, setV1] = useState('a');
  const [v2, setV12] = useState('b');
  return <div>Text</div>;
};

When called, React will, internally, now have something like the following:当被调用时,React 将在内部具有如下内容:

[ // array of all stateful values for this rendered component
  'a', // corresponds to the stateful value of the first useState
  'b', // corresponds to the stateful value of the second useState
]

These internal state values are changed when the state setter is called (eg setV1 ), and then when the component gets re-rendered, the new stateful values (coming from React internals) are then returned by useState .这些内部 state 值在调用 state 设置器时更改(例如setV1 ),然后当重新渲染组件时,新的有状态值(来自 React 内部)然后由useState返回。

When the state setter is passed a callback , eg, with your当 state 设置器传递一个回调时,例如,使用您的

setFullName((prevValue) => {

All that's really needed for this to work is for React to pass the current corresponding state value in React's internals as prevValue .为此,真正需要的是 React 将React 内部中当前对应的 state 值作为prevValue

When state is set, the corresponding value in React's internals gets updated, but there may be other synchronous code that runs before the component gets re-rendered, and the new values (coming from React internals) get returned by the next invocations of useState .当 state 设置时,React 内部的相应值会更新,但在组件重新渲染之前可能会运行其他同步代码,并且新值(来自 React 内部)由下一次调用useState That's why using the callback form of the state setter sometimes gives different results - the callback argument always comes from React's internals, but the state value returned by useState only refers to the state at the time the component was rendered .这就是为什么使用 state setter 的回调形式有时会给出不同的结果 - 回调参数总是来自 React 的内部,但 useState 返回的useState值仅指在组件呈现 E.5732 时的 Z9ED39E2EA931586B6A985A69。

For example例如

const [count, setCount] = useState(0);
const clickHandler = () => {
  setCount(count + 1); // sets the state in React's internals to 1
  setCount(count + 1); // sets the state in React's internals to 1, not 2;
                       // because `count` still refers to the initial value of 0
};
const [count, setCount] = useState(0);
const clickHandler = () => {
  setCount(count + 1); // sets the state in React's internals to 1
  setCount(prevCount => prevCount + 1); // sets the state in React's internals to 2
                                        // because `prevCount` comes directly from React's internals
};

But, for your code here, because multiple state changes are not occurring in the same render, there's no need to use the callback form - feel free to use the outside fullName identifier instead of using the prevValue and a callback.但是,对于您的代码,由于多个 state 更改不会发生在同一个渲染中,因此无需使用回调表单 - 随意使用外部fullName标识符而不是使用prevValue和回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM