Reactjs 从for循环中的多个连续异步调用调用多个`setState`钩子
我有以下功能组件:Reactjs 从for循环中的多个连续异步调用调用多个`setState`钩子,reactjs,react-hooks,use-state,react-functional-component,Reactjs,React Hooks,Use State,React Functional Component,我有以下功能组件: const MyComp = (props) => { const [dict, setDict] = useState({}); const myFunc = () => { [1, 2, 3].forEach(x => { fetch('something' + x) .then(res => res.json()) .then(res => { setDict
const MyComp = (props) => {
const [dict, setDict] = useState({});
const myFunc = () => {
[1, 2, 3].forEach(x => {
fetch('something' + x)
.then(res => res.json())
.then(res => {
setDict({...dict, [x]: res.y}); // <-------- PROBLEMATIC HERE
})
});
}
}
constmycomp=(道具)=>{
const[dict,setDict]=useState({});
常量myFunc=()=>{
[1,2,3].forEach(x=>{
获取('something'+x)
.then(res=>res.json())
。然后(res=>{
setDict({…dict[x]:res.y});//问题
您正在使用标准更新在循环中将状态更新排队。这意味着每次更新都使用该更新排队的渲染周期中的状态。每次后续更新都会覆盖以前的状态更新,因此最终结果是最后一次排队更新是为下一个渲染周期设置状态的更新
解决方案
使用函数状态更新。这里的区别是函数状态更新来自上一个状态,而不是来自上一个渲染周期的状态。它只需要从setDict({…dict,[x]:res.y})
到setDict(dict=>({…dict,[x]:res.y}))
setState
在回调的第一个参数中提供状态的当前值
因此,使用回调参数中的dict
值,而不是dict
const MyComp = (props) => {
const [dict, setDict] = useState({});
const myFunc = () => {
[1, 2, 3].forEach(x => {
fetch('something' + x)
.then(res => res.json())
.then(res => {
setDict((dict) => {...dict, [x]: res.y}); // <-------- PROBLEMATIC HERE
})
});
}
constmycomp=(道具)=>{
const[dict,setDict]=useState({});
常量myFunc=()=>{
[1,2,3].forEach(x=>{
获取('something'+x)
.then(res=>res.json())
。然后(res=>{
setDict((dict)=>{…dict[x]:res.y});//你能明确地解释一下你想要得到什么结果吗?我不太明白你的意思。我在for循环中调用了多个API,我想把所有的结果都存储在我的dict
中,但正如我在问题中所说的,React似乎抑制了多个setDict
@7ball太好了!如果答案和解释正确的话那么别忘了也请投票。干杯。
const MyComp = (props) => {
const [dict, setDict] = useState({});
const myFunc = () => {
[1, 2, 3].forEach(x => {
fetch('something' + x)
.then(res => res.json())
.then(res => {
setDict((dict) => {...dict, [x]: res.y}); // <-------- PROBLEMATIC HERE
})
});
}