【问题标题】:How to declare an object property with const如何用 const 声明对象属性
【发布时间】:2021-10-24 10:33:55
【问题描述】:

我需要从这里为formstate.title 声明一个变量:

    const initialState = { description: '', place: "", date: "", membersJoinedCounter: 0, title: ""  };
    
    const [formState, setFormState] = useState(initialState);

    function setInput(key, value,) {
        setFormState({ ...formState, [key]: value })
      }
    
    const userTitle = await API.graphql(graphqlOperation(getUserTitle, {id: userInfo.attributes.sub}))
    formState.title = userTitle.data.getUser.title;

如何实现?

【问题讨论】:

  • 我需要 formState.title 是可变的,以便每次用户更新标题时属性都会更新,现在它不会在数据库中更新
  • 你正在改变状态。用setFormState更新值formState
  • "formState.title" 已经是可变的。您是否在任何地方“设置状态”表单状态?
  • 请检查更新的代码

标签: javascript react-native react-hooks


【解决方案1】:

不清楚你想问什么,但是假设你想在获取数据后设置title值,你可以通过useState hook提供的setFormstate方法来实现(你不能直接将值设置为useState hook返回的formstate是不可变的)

在你的代码中替换下面的行

formState.title = userTitle.data.getUser.title

下面一个

setFormState(prev=>({...prev,title:userTitle.data.getUser.title}))

【讨论】:

  • 请检查更新的代码,如何在 setFormState 中添加 title 属性?每次用户更改标题值时,我都需要更新标题
  • @Tony "setInput" 已经这样做了。
  • 像 setInput("title",userTitle.data.getUser.title) 这样调用 setInput 函数就可以了
猜你喜欢
  • 2021-09-19
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
相关资源
最近更新 更多