在清除效果(从useEffect)期间如何访问状态(从useState)?

时间:2018-12-13 10:29:09

标签: reactjs react-hooks

考虑一个具有用户可以保存的受控输入的组件。使用onChangeuseState控制输入。某些应用程序效果可能导致Input卸下(请考虑无限滚动元素)。卸载时,我想访问当前值并将其持久保存到服务器。

当前,当我在卸载时访问value(useEffect钩子的返回函数)时,它的值不是当前值,而是初始值"initial text"

在不使用Redux或Context API的情况下,输入组件如何将当前value保存在卸载中?

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

const Input = () => {
  const [value, setValue] = useState("initial text");

  useEffect(() => {
    console.log(`on mount`);
    return () => {
      console.log(`Unmounts now, but the user did not save the input`);
      console.log(
        `I would like the application to have access to the current "value" to POST it to the server`
      );
      console.log(
        `But as you can see value now back to the initial state: "${value}"`
      );
    };
  }, []);

  return (
    <div>
      <input onChange={e => setValue(e.target.value)} />
      <div>(current value: {value})</div>
    </div>
  );
};

const App = () => {
  const [mounted, setMounted] = useState(true);

  return (
    <div>
      {mounted && <Input />}
      <button onClick={() => setMounted(false)}>Unmount input</button>
    </div>
  );
};

export default App;

沙箱:https://codesandbox.io/s/xvoz689mqz

0 个答案:

没有答案