如何使用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;

如何实现?

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

替换代码中的下一行

formState.title = userTitle.data.getUser.title

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