【问题标题】:nested state did not update having parsing error嵌套状态未更新解析错误
【发布时间】:2021-03-31 09:39:47
【问题描述】:

我正在尝试在上下文中更新我的嵌套状态,但它遇到了解析错误的问题。

这是我的GlobalState.js:

const [currentUser, setUser] = useState(props.serverUserData);


  const updateProfileImage = (picture) => {
    console.log('New Profile Image', picture);
    setUser({...currentUser, currentUser.picture: picture});
    console.log('currentUser2', currentUser.picture);
  };

此功能帮助用户上传他们的个人资料图片,但在上传成功后,图像在用户必须注销并重新登录后才会更改。所以我决定在用户​​不需要的上下文中创建一个 updateProfileImage 函数注销并重新登录以查看图像更改。

  const uploadImage = () => {
    const formData = new FormData();
    formData.append("file", imageSelected);
    formData.append("id", id);

    axios
      .post("/api/v1/users/upload/image", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      })
      .then((response) => {
        updateUserAvatar(response.data.data.imageUrl);
      });
  };

如何以正确的方式进行嵌套状态?

console.log(currentUser):

{id: "a19cac5c-ea25-4c9c-b1d9-5d6e464869ed", name: "Nhan Nguyen", email: "nhan13574@gmail.com", publicId: "Nh1615314435848", picture: "http://res.cloudinary.com/teammateme/image/upload/v1617173805/kqq7bnsujegvg2sgldox.svg", …}
email: "nhan13574@gmail.com"
id: "a19cac5c-ea25-4c9c-b1d9-5d6e464869ed"
isSessionValid: true
name: "Nhan Nguyen"
picture: "http://res.cloudinary.com/teammateme/image/upload/v1617173805/kqq7bnsujegvg2sgldox.svg"
publicId: "Nh1615314435848"
__proto__: Object

GlobalContext.js:

import React from "react";

const globalStateDefaults = {
  modals: {
    isAuthModalOpen: false,
    modalToDisplay: "signup",
    toggleModal: () => {},
    setModalToDisplay: () => {}
  },
  user: undefined,
  pageName: undefined,
  loading: false,
  teamProfileId: "",
  userProfileId: ""
};

export const GlobalContext = React.createContext(globalStateDefaults);

谁能帮我解决这个问题?我真的很感激。

【问题讨论】:

  • 能分享一下状态结构吗?
  • @amreshk005 刚刚添加到我的帖子中

标签: reactjs


【解决方案1】:

所以在状态解析中

setUser({...currentUser, currentUser.picture: picture});

你可以试试这个,而不是这个

setUser({...currentUser, picture: picture});

【讨论】:

  • 我的 currentUser.picture 好像还没有更新
  • 你更新状态的方式不对。
  • 您可以在渲染方法中控制您的状态。
猜你喜欢
  • 1970-01-01
  • 2020-03-14
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
相关资源
最近更新 更多