【问题标题】:Wait function completed before render in React Native在 React Native 中渲染之前等待函数完成
【发布时间】:2022-12-14 06:44:41
【问题描述】:

我面临着问题, 我正在为套接字 io 使用上下文。 在 App.js 中:


let loginInfo;
let socket = null;

// Listening notification on background or quit
messaging().setBackgroundMessageHandler(async remoteMessage => {
  // Init socket,
  // Start call
});

// Read AsyncStorage
const getLoginData = async () => {
  loginInfo = JSON.parse(await AsyncStorage._retrieveData('loginInfo'));
  if (loginInfo && loginInfo?.isJoinedRoom) {
    socket = io(loginInfo.url, {timeout: 10000, reconnection: false});
    
    // Here print later
    console.log('socket in appjs: ', socket); // 1 -> Socket in here assigned
  }
};
getLoginData();

const App = () => {
  // here print first
  console.log('Socket in appjs 2', socket); // 2 -> Socket in here is null
  return (
    <>
      <SocketProvider value={socket}>
        <MainContainer />
      </SocketProvider>
    </>
  );
};

export default App;

我想等待功能 getLoginData 在呈现应用程序之前完成。值始终为 null 的 SocketProvider。

你能告诉我如何在渲染之前等待一个函数完成吗,谢谢。

我尝试在 getLoginData let completed = false 中设置另一个变量 并在 App.js 中使用但不起作用:

{completed ? (
        <SocketProvider value={socket}>
          <MainContainer />
        </SocketProvider>
      ) : (
        <></>
      )}

【问题讨论】:

标签: react-native rendering react-context


【解决方案1】:

completed 将不起作用,因为您在 getLoginData 中使用 completed = false 作为普通变量......您必须将其用作状态,即

const [completed, setCompleted] = useState(false);

然后在 getLoginData 函数中,完成后,将状态设置为 true

就像你在上面使用它一样使用它。

【讨论】:

  • 我想在函数组件的主体之外调用它。因此,当尝试在函数组件外部调用 hook 时,会抛出一个错误:“Hooks can only be called inside of a function component”
  • React 通常不能很好地处理组件外部的变量,尤其是在状态和渲染方面。我建议您将函数移动到组件内部。
猜你喜欢
  • 2021-11-21
  • 2019-02-10
  • 1970-01-01
  • 2018-05-02
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 2021-12-03
相关资源
最近更新 更多