Lek*_*123 3 javascript settimeout reactjs use-effect
我有这段代码,我的问题是为什么在我的答案函数中我得到了initialState。如何以正确的方式设置状态以在 setTimeout 函数的回调中获得正确的状态?
const App = () => {
const [state, setState] = useState({
name: "",
password: "",
});
useEffect(() => {
setState({ ...state, password: "hello" });
setTimeout(answer, 1000);
}, []);
const answer = () => {
console.log(state);
// we get initial State
};
return <div className="App"></div>;
};
Run Code Online (Sandbox Code Playgroud)
原因是关闭。
answer函数将始终记录调用state该函数时关闭的函数的值。setTimeout()
在您的代码中,由于函数在包含具有空值的对象setTimeout()时被调用,因此函数会记录该值,而不是记录更新的值。stateanswer
要记录状态的最新值,可以使用useRef()挂钩。该钩子返回一个对象,其中包含名为 的属性current,该属性的值是传递给 的参数useRef()。
function App() {
const [state, setState] = React.useState({
name: "",
password: "",
});
const stateRef = React.useRef(state);
React.useEffect(() => {
stateRef.current = { ...stateRef.current, password: 'hello'};
setState(stateRef.current);
setTimeout(answer, 1000);
}, []);
const answer = () => {
console.log(stateRef.current);
};
return <div></div>;
}
ReactDOM.render(<App/>, document.getElementById('root'));Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3202 次 |
| 最近记录: |