我正在尝试重新排列一个状态两次,但是,该状态仅在最后一次useState时生效,我可以使用什么来多次重新排列一个状态?
代码如下:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [array, setArray] = useState([6,2,5,4,1]);
// async update from useEffect
useEffect(() => {
updateArray(array,2,1)
updateArray(array,4,2)
}, []);
const updateArray = (localArray, to, from) => {
let tempArray = [...localArray];
tempArray.splice(to, 0, tempArray.splice(from, 1)[0]);
setArray(tempArray);
};
console.log("render", array);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);我知道有一种方法是使用setTimeOut并逐个更新,然而,如果我的状态重新渲染晚了,它最终会出现故障。还有别的选择吗?
我期望数组是6, 5,4,1,2,因为第一个更改为6,5,2,4,1,1,秒更改为6,5,4,1,2
然而,它只运行最后一个,变成6,2,4,1,5
预期输出
First setState: [6, 5, 4, 1, 2]
Second setState: [6, 5, 2, 4, 1]电流输出
Second setState: [6, 2, 4, 1, 5]我还能知道发生这种情况的原因吗?
CodeSandBox link
发布于 2021-01-22 17:17:20
问题
在渲染周期内将多个状态更新排入队列时,应使用功能状态更新从上一个状态进行更新,而不是从上一个渲染周期的状态进行更新。当发生后一种情况时,每个排队的更新都会覆盖前一个更新,因此最后一个更新获胜。
解决方案
使用功能状态更新。
useEffect(() => {
updateArray(2, 1);
updateArray(4, 2);
}, []);
const updateArray = (to, from) => {
setArray(prevState => {
const tempArray = [...prevState];
tempArray.splice(to, 0, tempArray.splice(from, 1)[0]);
return tempArray
});
};
发布于 2021-01-22 17:11:54
这应该是可行的:
useEffect(() => {
setArray(currentArray => updateArray(currentArray, 2, 1))
setArray(currentArray => updateArray(currentArray, 4, 2))
}, []);
const updateArray = (localArray, to, from) => {
let tempArray = [...localArray];
tempArray.splice(to, 0, tempArray.splice(from, 1)[0]);
return tempArray
};发布于 2021-01-22 17:12:02
当使用[]时,useEffect将仅运行一次
useEffect(() => {
updateArray(array,2,1)
updateArray(array,4,2)
}, []);remove []反复运行它
useEffect(() => {
updateArray(array,2,1)
updateArray(array,4,2)
});或者添加您正在等待更新的属性,这样当此属性更改时,useEffect将触发
useEffect(() => {
updateArray(array,2,1)
updateArray(array,4,2)
}, [array]);https://stackoverflow.com/questions/65842042
复制相似问题