无法理解特定调用中react js函数参数的setState?

Unable to understand setState of react js function paramters in a specific call?

      setListOfPosts(curPosts => {            
           let newPosts = [...curPosts];
       newPosts[newPosts.findIndex(p => p.id === postId)].alert = response.data;
        }
  });

//curPosts是一个数组实例还是完整数组??我的 listofPosts 是一个对象数组

您的 setState 调用需要 return newPosts,并且您正在使用展开运算符创建一个数组,这就是它作为对象数组返回的原因。

我不确定您想要的输出是什么,但是通过添加 return 函数,它将设置状态:

  setListOfPosts(curPosts => {            
              let newPosts = [...curPosts];
              newPosts[newPosts.findIndex(p => p.id === postId)].alert = response.data;
              return newPosts
            }
      });

这是未经测试的,但如果您的逻辑是正确的,应该 return 更新对象警报值的对象数组。

另一种选择是在调用 setState 之前执行您的逻辑,方法是创建一个 newState 数组,然后在不使用回调的情况下使用该新数组简单地更新状态。

如果您想向状态数组添加新对象或做一些保留初始状态的事情,回调函数很有用,在您的示例中,您可以在没有回调的情况下这样做:

  // Create a copy of the state array that you can manipulate
    const newPosts = [...newPosts]
    
      if (data.response) {
       // Add your logic to the state copy
       newPosts[newPosts.findIndex(p => p.id === postId)].alert = response.data;

       // Replace state with state copy
       setListOfPosts(newPosts)
      }

同样未经测试,但希望这能帮助您了解回调函数的使用以及正确的使用方法。