setState稍后更新组件一个状态

时间:2019-09-21 06:37:24

标签: javascript reactjs setstate

在下面的代码中,名称(或任何其他对象/不仅是字符串)仅在第二次更改后在组件中更新。在第三次更改中,它获得第二次更改值,依此类推,即状态落后了一步。

状态落后了

const [state,setState]=useState([]);

const onChange=(id)={
let vname="hello world";
const temp = state.map((item,i)=>{
if(i===id){
return vname;
}
return item;
});
setState(temp);
}

1 个答案:

答案 0 :(得分:3)

首先,该代码看起来有点不正确: onChange事件应该将事件解析为它。

尝试这样的事情:

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
  const [name, setName] = useState("");
  const [reg, setReg] = useState(["dog", "cat", "monkey"]);
  const [pujab, setPujab] = useState("");
  return (
    <div>
      <label htmlFor="name">firstName:</label>
      <input
        name="name"
        type="text"
        value={name}
        onChange={e => {
          const newFirstName = e.target.value;
          setName(newFirstName);
        }}
      />

      <div />

      <label htmlFor="play">ChangeList: </label>
      <input
        name="play"
        type="text"
        value={pujab}
        onChange={e => {
          const newPujab = e.target.value;
          setPujab(newPujab);
          console.log("iniitiitit");
          for (let i = 0; i < reg.length; i++) {
            if (reg[i] === e.target.value) {
              console.log("yessss");
              reg[i] = "welcome";
            }
          }
        }}
      />
      <p>Animal List: {reg.map(item => item + " ")}</p>
      <p>Changes: {name}</p>
      <p>Names: {pujab}</p>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我将其放在此处的codeandbox上:https://codesandbox.io/s/amazing-hodgkin-7x9nn