【问题标题】:How can i clear localStorage only avatar field when i upload avatar picture . React上传头像图片时如何清除localStorage only头像字段。反应
【发布时间】:2018-11-27 18:49:24
【问题描述】:

大家好,当我在我的项目中更改头像图片时。我可以成功上传,但由于 localStorage 数据没有改变。我试过这样;

this.state = {
  imageUrl: props.user && props.user.avatar,
};

我的功能就是这样

changeAvatar() {
  const profileDetail = cloneDeep(JSON.parse(localStorage.getItem('__PERSISTED_STORE__')));

  const isProfileDetailExist = profileDetail
    && profileDetail.user
    && profileDetail.user.signIn
    && profileDetail.user.info;

  if (isProfileDetailExist) {
    profileDetail.user.signIn.info.avatar = this.state.imageUrl;
  }

  localStorage.setItem('__PERSISTED_STORE__',
    JSON.stringify({
      user: profileDetail.user,
      language: profileDetail.language
    })
  );
}

我该怎么做。我的数据看起来像;

Preferences : { user: { singIn: {info : { ..... 里面有头像。 我只想改变头像。语言:...

【问题讨论】:

  • 您能否提供代码沙箱来解决您的问题或更多代码,例如您使用头像的组件以及您从哪里设置它?

标签: javascript reactjs local-storage


【解决方案1】:

问题是你如何设置你的状态

    this.state = {
  imageUrl: props.user && props.user.avatar,
};

根据您的代码,imageUrl 是布尔值。如果你想分配头像位置(这是字符串),你应该使用

this.state = {
  imageUrl: props.user && props.user.avatar ? props.user.avatar: '',
};

如果 props.user.avatar && props.user 为 true,则会将 imageUrl 状态设置为 props.user.avatar。

【讨论】:

  • 不正确。 && 评估条件,如果 props.user 为真,则返回 props.user.avatar。和 props.user 一样吗? props.user.avatar : null;
  • @Simas.B 感谢您的提示。这些天我一直在写额外的代码
  • 在上面的代码中,props.user 和 props.user.avatar 都必须为真,语句才能返回 props.user.avatar。否则它将返回 ' ' ...它在三元运算符中的工作方式类似。之前的一切?如果它应该返回 props.user.avatar,则必须评估为 true。
猜你喜欢
  • 2011-08-16
  • 2021-11-10
  • 1970-01-01
  • 2023-01-19
  • 2020-01-21
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 2014-08-31
相关资源
最近更新 更多