Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 从for循环中的多个连续异步调用调用多个`setState`钩子_Reactjs_React Hooks_Use State_React Functional Component - Fatal编程技术网

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
      })
  });
}