【问题标题】:How to handle Async function response in react native and save in useState?如何在本机反应中处理异步函数响应并保存在useState中?
【发布时间】:2021-04-06 18:04:23
【问题描述】:
const [confirm, setConfirm] = useState(null);

const signIn = async phoneNumber => {
  console.log('Entered into signIn Function');
  setTextInputState(false);
  setSendOtpButtonState(true);

  const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
  console.log('This is conformation1' + JSON.stringify(confirmation));
  setSendOtpButtonState(true);
  setOtpInputState(true);

  let res = confirmation;
  setConfirm(res);

  console.log('This is conformation2' + JSON.stringify(confirm));
};

如何在 useState 中设置构象。当我们第一次进入 signIn 函数时,将 useState 值设置为 null 并且第二次在 useState 中设置值。我想第一次设置值。

【问题讨论】:

  • 共享完整组件,我认为在这种情况下你也需要useEffect

标签: javascript android reactjs firebase react-native


【解决方案1】:

这可能会有所帮助

const signIn = async (phoneNumber) => {

  const [confirm, setConfirm] = useState(null);
  ...

  useEffect(async () => {
    const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
    console.log("This is conformation1" + JSON.stringify(confirmation));
    setSendOtpButtonState(true);
    setOtpInputState(true);

    let res = confirmation;
    setConfirm(res);
  }, []);

  console.log("This is conformation2" + JSON.stringify(confirm));
};

【讨论】:

  • 我收到了这个错误。错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一: 1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能有多个 React 副本同一个应用
  • 我用你的代码更新了,但它不起作用
  • 还是同样的问题?无效的 Hook 调用?
  • 同样的问题先生。
猜你喜欢
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多