仅在页面加载时轻松将数据加载到 React Form 中

Easily loading data into React Form only when page loads

我正在尝试在 React 应用程序中实现 'profile details' 功能。

当用户导航到此处时我希望页面执行的操作:

我正在使用 useState 管理 formData 并使用 Effect Hook 在呈现页面时预填充字段(从 redux 存储获取值)。

我也在使用 React router 将此路由设为私有,并重定向未通过身份验证的用户。

一切正常,除了我的 useEffect 挂钩 - 这给我带来了很多麻烦:

  useEffect(() => {
    getCurrentProfile();
    if (profile !== null) {
      setFormData({
        location: loading || !profile.location ? '' : profile.location,
        gender: loading || !profile.gender ? '' : profile.gender,
        age: loading || !profile.age ? '' : profile.age,
        bio: loading || !profile.bio ? '' : profile.bio,
      });
    }
  }, [getCurrentProfile, loading]);

注意:if 语句用于防止未经身份验证的用户访问此路由时应用程序崩溃。我收到 TypeError: Cannot read 属性 'location' of null if I don't have some kind of blocker from this weird way of updateing state.

我运行进入以下问题:

  1. 当前的实现,我得到一个 linter 错误:

React Hook useEffect 缺少依赖项:'profile'。任何一个 包含它或删除依赖项数组 react-hooks/exhaustive-deps

这 "works" 我想要的方式。如果我输入一些东西,然后 refresh/change 页面,表单会呈现更新的信息。本地状态仍然由 useState 钩子控制,因为用户经常更改表单并选择不将信息提交到数据库。

  1. 如果我添加配置文件依赖项,每当我在这些字段中输入一个值时,页面只会不断重新呈现并杀死我输入的所有内容,因为它不是数据库的先前状态。

我不明白为什么会发生这种情况,或者预填充字段的最佳做法是什么,同时仍然可以访问本地控制的提交状态。

这当然会消除 linter 错误,但它破坏了我的预期功能。这是个问题吗?

我只是想让这个东西在页面加载后 运行,以便用户知道当前的配置文件值是什么。

有什么建议吗?也许我的整个方法对于我要尝试做的事情都是错误的。如果需要,很乐意提供更多详细信息。

通过重构和处理子组件中的本地状态解决了这个问题。