如何在反应中更新上下文状态

时间:2021-04-01 01:55:40

标签: node.js reactjs

我遇到一个问题,当用户上传他们的个人资料图片时,它没有改变,用户必须注销并重新登录才能完成更改。

这是我的后端如何从客户端获取图像并将其存储在 cloudinary 上:

profilesController.js:

exports.updateAvatar = async (req, res) => {
  // Find user with matching token
  // const updates = [];
  const updateUserAvatar = await models.User.findOne({
    where: {
      id: req.id,
    },
  });

  // Was user found?
  if (updateUserAvatar === null) {
    return res.status(200).json({
      validationErrors: {
        errors: [
          {
            msg: "Reset is invalid or has expired.",
          },
        ],
      },
    });
  }

    // Update user with new info
    models.User.update(
    {
      picture: req.imageUrl,
    },
    {
      where: {
        id: updateUserAvatar.dataValues.id,
      },
    }
    );
  
  console.log(updateUserAvatar);

在控制台它应该给我一个新的图片网址,但它只保留旧的图片网址

这是我的profilesAPI,我的路线是:

router.post('/upload/image', function (req, res, next) {

  const dUri = new Datauri();

  const dataUri = (req) => dUri.format(path.extname(req.name).toString(), req.data);

  if (req.files !== undefined && req.files !== null) {
    const { file, id } = req.files;

    const newFile = dataUri(file).content;
   
    cloudinary.uploader.upload(newFile)
      .then(result => {
        const imageUrl = result.url;
        const data = {id : req.body.id, imageUrl };
      updateAvatar(data);
      return res.status(200).json({ message: 'Success', data: { imageUrl } });
    }).catch(err =>  res.status(400).json({message:'Error', data: { err}}));
  } else {
    return res.status(400).json({ message: 'Error' });
  }

});

这就是我的后端代码。这是我将图像发送到服务器的前端:

这里是帮助用户将图片发送到服务器的方法:

const UserCard = ({ name, userEmail, isVerified, id, updateUserAvatar, currentUser }) => {
  const [selectedValue, setSelectedValue] = useState("a");
  const handleChange = (event) => {
    setSelectedValue(event.target.value);
  };

  const [imageSelected, setImageSelected] = useState("");

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

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

  useEffect(() => {
    if (imageSelected !== '') {
      uploadImage();
    }
     
  }, [imageSelected]);

  return (
    <div className="avatar--icon_profile">
      <Card className="profile--card_container">
        <CardContent>
          {currentUser.picture ? (
            <div>
              <input
                className="my_file"
                type="file"
                ref={inputFile}
                onChange={(e) => setImageSelected(e.target.files[0])}
              />
                <div className="profile-image">                
                  <Avatar
                      src={currentUser.picture}
                      alt="Avatar"
                      className="avatar--profile_image"
                      onClick={onButtonClick}
                  />
                  </div>
            </div>

这是我的全局状态。我试图在我的上下文中更新嵌套状态,但似乎没有用。

const GlobalState = (props) => {
  // User State -----------------------------------------------------------------------------
  const [currentUser, setUser] = useState(props.serverUserData);

 console.log(currentUser)

  const updateUser = (userData) => {
    setUser(userData);  
  };


  // This method is passed through context to update currentUser Avatar

  const updateUserAvatar = (picture) => {
    setUser({ ...currentUser, picture: picture });  
  };

 const providerValues = {
    currentUser,
    updateUser,
    updateUserAvatar,
  };

  return (
    <GlobalContext.Provider value={providerValues}>
      {props.children}
    </GlobalContext.Provider>
  );
};

export default GlobalState;

这是我的 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/v1617229506/gnlooupiekujkrreerxn.png", …}
email: "nhan13574@gmail.com"
id: "a19cac5c-ea25-4c9c-b1d9-5d6e464869ed"
isSessionValid: true
name: "Nhan Nguyen"
picture: "http://res.cloudinary.com/teammateme/image/upload/v1617229506/gnlooupiekujkrreerxn.png"
publicId: "Nh1615314435848"
__proto__: Object

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

添加了 GlobalContext.js:

从“反应”导入反应;

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

export const GlobalContext = React.createContext(globalStateDefaults);

1 个答案:

答案 0 :(得分:0)

您需要使用尝试更新用户状态的上下文。

const {currentUser, updateUser, updateUserAvatar} = React.useContext(GlobalContext)

然后你可以打电话

updateUserAvatar(response.data.data.imageUrl)