【问题标题】:How to called async function in useEffect after submiting in react native?react native提交后如何在useEffect中调用异步函数?
【发布时间】:2021-04-23 03:20:08
【问题描述】:

我希望一旦用户单击提交按钮以重新加载整个“页面”并调用 useEffect 函数。当前的行为是当用户点击提交按钮时,根本没有调用useEffect函数。就好像提交后没有直接重新加载一样。我不知道这是否是由于异步和等待。我给你代码:

使用效果():

useEffect(() => {

    console.log('test useEffect');

    (async () => {
      try {
        const value = await AsyncStorage.getItem('authToken_Lust');
        if(value !== null) {
          const decodedValue = jwt_decode(value);
          const current_time = Date.now() / 1000;
          if(decodedValue.exp < current_time) {
            setMessage('Vous n\'êtes plus connecté(e).')
          } else {
            setMessage('Vous êtes connecté(e)');
          }
        }
      } catch(err) {
        console.log(err);
      }
    })();

  }, []);

用户点击提交后调用的函数代码:

const onSubmit = async () => {
    setLoading(true)
    await fetch('http://192.168.1.36:3000/api/users/login', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: email,
        password: password
      })
    })
    .then((response) => response.json())
    .then(async (res) => {
      if(res.error) {
        setMessage(res.error);
      } else {
        try {
          await AsyncStorage.setItem('authToken_Lust', res.token);
        } catch (err) {
          console.log(err);
        }
      }
    })
    .catch((err) => console.log(err))
    .finally(() => setLoading(false));
  }

坦克

【问题讨论】:

    标签: javascript reactjs typescript react-native use-effect


    【解决方案1】:
    1. 创建一个状态变量以指示凭据已成功提交(在此组件中)。

      const [submitted, setSubmitted] = useState(1);
      
    2. 每当您在 onSubmit 中从您的 api 获得响应时更改此状态变量(以某种方式更新组件):

      try {
          await AsyncStorage.setItem('authToken_Lust', res.token);
          setSubmitted(submitted+1);
      }
      
    3. 从您的useEffect 中完全删除依赖数组或更改它以响应submitted 值更改;

      useEffect(() => {
          // ...
      }, [submitted]);
      

    【讨论】:

      【解决方案2】:

      您需要对代码进行以下更改:

      const onSubmit = () => {
        setIsSubmitted(true);
        setLoading(true);
        fetch("http://192.168.1.36:3000/api/users/login", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            email: email,
            password: password,
          }),
        })
          .then((response) => response.json())
          .then(async (res) => {
            if (res.error) {
              setMessage(res.error);
            } else {
              try {
                await AsyncStorage.setItem("authToken_Lust", res.token);
              } catch (err) {
                console.log(err);
              }
            }
          })
          .catch((err) => console.log(err))
          .finally(() => setLoading(false));
      };
      
      const asyncEffect = async () => {
        try {
          const value = await AsyncStorage.getItem("authToken_Lust");
          if (value !== null) {
            const decodedValue = jwt_decode(value);
            const current_time = Date.now() / 1000;
            if (decodedValue.exp < current_time) {
              setMessage("Vous n'êtes plus connecté(e).");
            } else {
              setMessage("Vous êtes connecté(e)");
            }
          }
        } catch (err) {
          console.log(err);
        }
      };
      
      useEffect(() => {
        if (isSubmitted) {
          console.log("test useEffect");
          asyncEffect();
        }
      }, [isSubmitted]);
      

      【讨论】:

      • 我通过添加 isSubmitted 状态进行了更改,但是当用户提交时,仍然没有调用 useEffect。当我保存文件而 isSubmitted 未更改时,我什至会在控制台上进行“useEffect 测试”。
      【解决方案3】:

      考虑到您给出的建议,我更改了所有代码:

      const [submitted, setSubmitted] = useState(1);
      
      useEffect(() => {
          console.log("test useEffect");
          asyncEffect();
        }, [submitted]);
      
        const asyncEffect = async () => {
          try {
            const value = await AsyncStorage.getItem("authToken_Lust");
            if (value !== null) {
              const decodedValue = jwt_decode(value);
              const current_time = Date.now() / 1000;
              if (decodedValue.exp < current_time) {
                setMessage("Vous n'êtes plus connecté(e).");
              } else {
                setMessage("Vous êtes connecté(e)");
              }
            }
          } catch (err) {
            console.log(err);
          }
        };
      
        const onSubmit = () => {
          setSubmitted(submitted+1);
          setLoading(true);
          fetch("http://192.168.1.36:3000/api/users/login", {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              email: email,
              password: password,
            }),
          })
          .then((response) => response.json())
          .then(async (res) => {
            if (res.error) {
              setMessage(res.error);
            } else {
              try {
                await AsyncStorage.setItem("authToken_Lust", res.token);
              } catch (err) {
                console.log(err);
              }
            }
          })
          .catch((err) => console.log(err))
          .finally(() => setLoading(false));
        };

      当我单击提交按钮时,控制台日志工作正常(我在控制台上看到“test useEffect”),但似乎没有调用 asyncAffect() 函数。 asyncEffect() 中的 setMessage 完全没有变化。

      【讨论】:

        猜你喜欢
        • 2019-11-12
        • 2020-09-02
        • 1970-01-01
        • 2017-08-13
        • 2017-07-20
        • 2019-04-04
        • 2022-01-25
        • 1970-01-01
        相关资源
        最近更新 更多