首页 > 解决方案 > 如何用 const 声明对象属性

问题描述

我需要为此声明一个变量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;

如何做到这一点?

标签: javascriptreact-nativereact-hooks

解决方案


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

替换代码中的以下行

formState.title = userTitle.data.getUser.title

低于一个

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


推荐阅读