【问题标题】:Formik's setFieldValue doesn't work with value coming from Context APIFormik 的 setFieldValue 不适用于来自 Context API 的值
【发布时间】:2020-05-22 01:04:43
【问题描述】:

我在我的 React Native 应用程序中使用 AWS Amplify 和 Formik。有一个屏幕,其中将显示成员列表,当屏幕加载时,当前用户将默认添加到列表中。这是我之前拥有的并且完美运行(我可以在屏幕上的列表中看到当前用户)。

  useEffect(() => {
    if (values.members.length === 0) {
       Auth.currentAuthenticatedUser().then(user => {
         const owner: Member = {
           id: user.attributes.sub,
           name: user.attributes.name,
         };

         setFieldValue('members', [owner]);
       });
    }
  }, []);

但是,然后,我创建了一个UserContext,并决定用来自UserContext 的用户替换对放大函数Auth.currentAuthenticatedUser() 的调用。这是新代码:

  const { user } = useContext(UserContext);

  useEffect(() => {
    if (values.members.length === 0) {
      const owner: Member = {
        id: user.attributes.sub,
        name: user.attributes.name,
      };

      console.log("Owner", owner); // This displays the current user in the console

      setFieldValue('members', [owner]);
    }
  }, []);

正如我在代码中评论的那样,console.log() 显示当前用户,因此UserContext 工作正常,但由于某种原因setFieldValue 不起作用。有谁知道为什么会发生这种情况?

更新:

我想如果我将setFieldValue() 放在setTimeout 内的第二个代码中,它会起作用。但是,在这种情况下,如果我将useEffect(() => {}, []) 更改为useEffect(() => {}, [user]),它是否也可以工作?

【问题讨论】:

    标签: reactjs react-native formik react-context


    【解决方案1】:

    您的问题是因为existing formik issue。因此,在修复之前,只需使用 setTimeout 或您提到的解决方案即可。

    如果有用,请参阅同一链接中提到的其他一些替代方案。

    【讨论】:

    • 那就解释了。谢谢!我非常确定这与 Formik 没有任何关系,以至于我什至没有在那里寻找问题。在这种情况下,我在另一个答案中的解决方案比使用setTimeout() 更好。
    【解决方案2】:

    这就是我最终要做的。我将其发布为答案,但我仍在寻找关于为什么会发生这种情况的答案。

      const { user } = useContext(UserContext);
      const [owner, setOwner] = useState(null as Member | null);
    
      useEffect(() => {
        if (values.members.length === 0) {
          setOwner({
            id: user.attributes.sub,
            name: user.attributes.name,
          });
        }
      }, []);
    
      useEffect(() => {
        setFieldValue('members', [owner]);
      }, [owner]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 2011-10-09
      • 2021-06-26
      相关资源
      最近更新 更多