【问题标题】:Using setState inside useEffect on updating forms在 useEffect 中使用 setState 更新表单
【发布时间】:2020-01-31 20:36:51
【问题描述】:

所以我编写了有关在 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]);

【问题讨论】:

    标签: reactjs forms react-redux react-hooks


    【解决方案1】:

    您应该等待后端数据,然后更新您的本地状态。您可以使用 async/await 或 Promise 语法来执行此操作。使用 async/await 语法:

    
    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();
    
        }, []);
    
    

    【讨论】:

      【解决方案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]);
      

      【讨论】:

        猜你喜欢
        • 2021-10-02
        • 2021-10-17
        • 2021-04-19
        • 1970-01-01
        • 2021-09-06
        • 2021-03-10
        • 2022-07-26
        • 2020-10-20
        • 2023-04-01
        相关资源
        最近更新 更多