在渲染组件之前反应本机提取

问题描述 投票:1回答:1

我正在创建一个Reat Native应用程序,该应用程序连接到从中获取数据的API。

我正在使用React Navigation来处理导航。该应用程序具有堆栈导航器和底部选项卡导航器。 StackNavigator有4个屏幕:

  • SignupScreen处理创建帐户;
  • LoginScreen用于一手登录;
  • SplashScreen检查本地令牌并自动登录用户;
  • A LoadingScreen触发对API的初始提取调用,将响应存储在状态中并导航到MainFlow屏幕;
  • 一个包含MainFlowTabNavigator屏幕。

TabNavigator有两个屏幕,FeedScreenAccountMore,初始屏幕为FeedScreen

注册/登录/本地流均正常。

问题:成功登录用户后,LoadingScreen会触发API调用,但是在数据处于状态之前会呈现MainFlow组件。由于MainFlow中的组件需要数据,因此会引发错误。仅当数据存在后,如何才能渲染FeedScreen组件?

LoadingScreen中,我从上下文对象useEffect触发了QuestionContext的API调用:

const LoadingScreen = ({ navigation }) => {
  const [loading, setLoading] = useState(true);
  const { state: authState } = useContext(AuthContext);
  const { getQuestionsForUser, getAllQuestions } = useContext(QuestionContext);

  useEffect(() => {
    getAllQuestions();
  }, []);

  return (
    <View style={styles.container}>
      <YonStatusBar backgroundColor="#310B3B" />
      <Image source={splashLogo} containerStyle={styles.splashLogo} />
      <ActivityIndicator />
    </View>
  );
};

export default LoadingScreen;

[getAllQuestionsQuestionContext中的一个函数,该函数进行API调用并导航到FeedScreen:]]

const getAllQuestions = (dispatch) => {
  return async () => {
    try {
      const token = await AsyncStorage.getItem('token');
      const config = { headers: { Authorization: `Bearer ${token}` } };
      const response = await yonyonApi.get(`/questions`, config);
      dispatch({ type: 'GET_ALL_QUESTIONS', payload: response.data });
      RootNavigation.navigate('MainFlow');
    } catch (e) {
      console.log(e);
    }
  };
};

getAllQuestions正常工作:API调用成功,并且可以看到响应存储在状态中。但是,它会在发生这种情况之前导航到MainFlow

最后,这是FeedScreen

const FeedScreen = () => {
  const { state: questionState } = useContext(QuestionContext);

  return (
    <ScrollView style={styles.container}>
      {console.log(questionState.questions)}
      <View style={styles.listContainer}>
        <QuestionCard />
      </View>
    </ScrollView>
  );
};

export default FeedScreen;

FeedScreen呈现需要QuestionCard中数据的questionState。这就是引发错误的原因:QuestionCard在数据处于状态之前被渲染。

一旦必要的数据处于状态,如何使导航仅导航到FeedScreen?或者,在数据不存在的情况下渲染QuestionCard以外的内容,一旦数据在questionState中,则渲染QuestionCard

我正在创建一个Reat Native应用程序,该应用程序连接到从中获取数据的API。我正在使用React Navigation来处理导航。该应用程序具有堆栈导航器和底部选项卡导航器。 ...

reactjs react-native react-navigation render use-effect
1个回答
0
投票

对我来说,我将使用屏幕而不是两个屏幕,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.