【问题标题】:Simple react state not changing on first request简单的反应状态不会在第一次请求时改变
【发布时间】:2020-11-10 11:57:19
【问题描述】:

我不知道为什么,但出于某种原因,在这个简单的演示中,您必须提交两次表单才能更改 testState 的值。应该发生的情况是,每当您提交表单(第一次)时,testState 应该将其值更改为 "changed",但它似乎只会在第二次、第三次(等等)提交时发生。

任何人都可以在这里发现任何明显的东西吗?代码如下:

import React, { useState } from "react";

const App = () => {
  const [testState, setTestState] = useState("unset");
  const [inputValue, setInputValue] = React.useState("");
  const submitMe = e => {
    e.preventDefault();
    setTestState("changed");
    console.log("name change Fn", inputValue, 'testState', testState); // should log 'changed' after first submit
  };

  const onNameChange = e => {
    console.log(e)
  }

  return (
    <>
      <form onSubmit={submitMe}>
        <input
          placeholder="the value"
          type="text"
          onChange={e => onNameChange(e.target.value)}
        />
        <button type="submit">Submit</button>
      </form>
    </>
  );
};

export default App;

还有一个 stackblitz 演示:https://stackblitz.com/edit/react-joe6jg

该值应与表单提交一起记录到控制台。

谢谢。

【问题讨论】:

  • 状态是异步更新的。使用useEffect 挂钩记录更新的状态。在调用状态更新函数后立即记录状态将记录旧值。

标签: reactjs


【解决方案1】:

根据docs中的解释:

setState() 不会立即改变 this.state 而是创建一个 等待状态转换。调用 this 后访问 this.state 方法可能会返回现有值。

不保证 setState 调用的同步操作 并且调用可能会被批处理以提高性能。

您应该监控 useEffect 中的状态变化。

import React, { useState, useEffect } from "react";

const App = () => {
  const [testState, setTestState] = useState("unset");
  const [inputValue, setInputValue] = React.useState("");
  const submitMe = e => {
    e.preventDefault();
    setTestState("changed");
  };

  useEffect(() => {
    console.log("name change Fn", inputValue, "testState", testState);
  }, [inputValue, testState]);

  const onNameChange = e => {
    console.log(e);
  };

  return (
    <>
      <form onSubmit={submitMe}>
        <input
          placeholder="the value"
          type="text"
          onChange={e => onNameChange(e.target.value)}
        />
        <button type="submit">Submit</button>
      </form>
    </>
  );
};

export default App;

【讨论】:

    【解决方案2】:

    您无法在设置状态后立即获得更新的状态。 您需要通过useEffect 获取。

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

    【讨论】:

      【解决方案3】:

      useStates set 方法在某种程度上是异步的。因此,只有在当前范围代码完成后,您的变量才会触发组件的更改,然后您才能记录它。您可以尝试将console.log 放入组件中(而不是useEffect),看看您的组件如何变化。

      但您也可以在 useEffect 中看到它,这样日志记录就不会在每次重新渲染时触发:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-27
        • 2018-08-11
        • 2018-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-06
        相关资源
        最近更新 更多