考虑一个具有用户可以保存的受控输入的组件。使用onChange
和useState
控制输入。某些应用程序效果可能导致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;