在 React + axios 中处理 UI 更新

问题描述 投票:0回答:1

最近我偶然发现了如何正确处理 UI 更新的困境。我在工作中使用的堆栈是React + axios。假设本地状态中有一个用户配置文件对象,并且用户想要更新他的名字。哪种方式更好?请让我知道我在这里缺少什么?

    const handleUpdateUserProfile = async (newUserName) => {
      const originalUserName = userProfile.name;

      // Optimistically update the UI
      setUserProfile(prev => ({ ...prev, name: newUserName }));

      // Try to send the database request
      try {
        await axios.post("/some-endpoint", {...userProfile, name: newUserName });
      } catch (error) {
        // In case of an error go back to the previous value
        setUserProfile(prev => ({...prev, name: originalUserName}));
        console.error(error);
      }
    }

    const handleUpdateUserProfile = async (newUserName) => {
      const originalUserProfile = structuredClone(userProfile);
      const updatedUserProfile = { ...originalUserProfile, name: newUserName }

      // Optimistically update the UI
      setUserProfile(updatedUserProfile);

      // Try to send the database request
      try {
        await axios.put("/some-endpoint", updatedUserProfile);
      } catch (error) {
        // In case of an error go back to the previous value
        setUserProfile(originalUserProfile);
        console.error(error);
      }
    }

我知道我还应该检查发布请求的响应对象中的状态代码。

感谢所有建议。

javascript reactjs api user-interface axios
1个回答
0
投票

最少代码方法,将简单地推迟更新,直到 API 完成并成功。

const handleUpdateUserProfile = (newUserName) => {
  const originalUserProfile = structuredClone(userProfile);
  const updatedUserProfile = { ...originalUserProfile, name: newUserName }

    await axios.put("/some-endpoint", updatedUserProfile).then((response: any) => {
      if(response.status === 'SUCCESS') {
        setUserProfile(updatedUserProfile);
      }
    }).catch(error =>  {
      // In case of an error go back to the previous value
      console.error(error);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.