在useEffect中使用setState更新表单

时间:2020-01-31 20:36:51

标签: reactjs forms react-redux react-hooks

所以我是关于在React中使用Forms的代码教程。

我打算做什么:显示当前用户导航到“ / 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]);

2 个答案:

答案 0 :(得分:0)

您应该等待后端数据,然后更新本地状态。您可以使用async / await或Promise语法来做到这一点。使用异步/等待语法:


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();

    }, []);

答案 1 :(得分:0)

您要将其分为2种效果:

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]);