因此,我是关于如何在React中使用表单的代码教程。
我打算做的事情,:当前用户导航到“/update-profile”路径==>部分表单输入,这是用户之前已经做过的,如图所示。
当前发生的事情--:对后端的API调用很好。存储到状态的配置文件数据,但是所有的表单值都没有显示任何内容,尽管其中的一些部分以前已经填充过了。
我已经复制粘贴源文件,但问题仍然发生,而在视频中,它的工作很好。我的密码有什么问题吗?
const EditProfile = ({
profileState: { profile, loading },
getCurrentProfile
}) => {
const [formData, setFormData] = useState({
company: "",
website: "",
location: "",
status: "",
skills: "",
bio: ""
});
useEffect(() => {
getCurrentProfile();
setFormData({
company: loading || !profile.company ? "" : profile.company,
website: loading || !profile.website ? "" : profile.website,
location: loading || !profile.location ? "" : profile.location,
status: loading || !profile.status ? "" : profile.status,
skills: loading || !profile.skills ? "" : profile.skills.join(","),
bio: loading || !profile.bio ? "" : profile.bio
});
}, [loading, getCurrentProfile]);发布于 2020-01-31 20:53:19
您应该等待后端数据,然后更新本地状态。您可以使用异步/等待或承诺语法来完成此操作。使用异步/等待语法:
useEffect(() => {
async function getAPI() {
await getCurrentProfile();
setFormData({
company: loading || !profile.company ? "" : profile.company,
website: loading || !profile.website ? "" : profile.website,
location: loading || !profile.location ? "" : profile.location,
status: loading || !profile.status ? "" : profile.status,
skills: loading || !profile.skills ? "" : profile.skills.join(","),
bio: loading || !profile.bio ? "" : profile.bio
});
}
getAPI();
}, []);发布于 2020-01-31 20:59:07
你想把它分成两个效果:
useEffect(() => {
getCurrentProfile();
}, [getCurrentProfile]);
useEffect(() => {
setFormData({
company: loading || !profile.company ? "" : profile.company,
website: loading || !profile.website ? "" : profile.website,
location: loading || !profile.location ? "" : profile.location,
status: loading || !profile.status ? "" : profile.status,
skills: loading || !profile.skills ? "" : profile.skills.join(","),
bio: loading || !profile.bio ? "" : profile.bio
});
}, [loading, profile]);https://stackoverflow.com/questions/60010902
复制相似问题