首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在更新表单时使用setState内部的useEffect

在更新表单时使用setState内部的useEffect
EN

Stack Overflow用户
提问于 2020-01-31 20:36:51
回答 2查看 122关注 0票数 0

因此,我是关于如何在React中使用表单的代码教程。

我打算做的事情,:当前用户导航到“/update-profile”路径==>部分表单输入,这是用户之前已经做过的,如图所示。

当前发生的事情--:对后端的API调用很好。存储到状态的配置文件数据,但是所有的表单值都没有显示任何内容,尽管其中的一些部分以前已经填充过了。

我已经复制粘贴源文件,但问题仍然发生,而在视频中,它的工作很好。我的密码有什么问题吗?

代码语言:javascript
复制
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]);
EN

回答 2

Stack Overflow用户

发布于 2020-01-31 20:53:19

您应该等待后端数据,然后更新本地状态。您可以使用异步/等待或承诺语法来完成此操作。使用异步/等待语法:

代码语言:javascript
复制
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();

    }, []);
票数 0
EN

Stack Overflow用户

发布于 2020-01-31 20:59:07

你想把它分成两个效果:

代码语言:javascript
复制
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]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60010902

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档