UseEffect 使用改变状态的旧值

时间:2021-01-06 11:54:05

标签: javascript reactjs use-effect

const [text, setText] = useState('');
useEffect(() => async () => {
  try {
    const response = await axios.post(
      'http://localhost:3001/changed',
      { text: text },
      { withCredentials: true }
    );
    console.log(response.data.text);
  } 
  catch (e) { 
    console.log(e);
  }
}, [text]);

我也有这样的文本输入:

<input type="text" onChange={ (e) => setText(e.target.value) } />

后端正在返回相同的发布对象。问题是,当我输入第一个字符时,useEffect 会记录一个空字符串,而当我输入第二个字符时,useEffect 只会记录第一个字符。

当我在输入字段中输入第三个字符时,useEffect 会记录前两个字符。它落后一个字符。为什么会这样?

2 个答案:

答案 0 :(得分:0)

那是因为您不是调用 useEffect-hook 中的异步函数,而是返回它。这意味着它会在下一次 text 变量更改后被调用。

试试这个:

// declare the function somewhere OUTSIDE your component
async function f(test) {  
  try {
    const response = await axios.post( 
      http://localhost:3001/changed`, 
      {text}, 
      {withCredentials: true}
    );
    console.log(response.data.text);
  } 
  catch (e) { 
    console.log(e);
  }
}

// and in your component:

const [text , setText] = useState("");

useEffect(() => {
  f(text);    // call it and don't return anything
}, [text]);

https://reactjs.org/docs/hooks-effect.html

答案 1 :(得分:0)

你可以简单地这样做:working demo

export default function App() {
  const [text, setText] = useState("");
  useEffect(() => {
    console.log("number is", text);
    async function makeCall() {
      try {
        const response = await axios.post(
          `http://localhost:3001/changed`,
          { text: text },
          { withCredentials: true }
        );
        console.log(response.data.text);
      } catch (e) {
        console.log(e);
      }
    }
    makeCall();
  }, [text]);

  return (
    <div className="App">
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
    </div>
  );
}