【发布时间】:2020-09-13 02:10:32
【问题描述】:
我正在创建一个 Reat Native 应用程序,该应用程序连接到它从中获取数据的 API。
我正在使用 React Navigation 来处理导航。该应用程序有一个堆栈导航器和一个底部选项卡导航器。 StackNavigator 有 4 个屏幕:
-
SignupScreen负责创建帐户; -
LoginScreen用于手动登录; -
SplashScreen检查本地令牌并自动登录用户; -
LoadingScreen触发对 API 的初始 fetch 调用,将响应存储在 state 中并导航到MainFlow屏幕; - 包含
TabNavigator的MainFlow屏幕。
TabNavigator 有两个屏幕,FeedScreen、Account 和 More,其中初始屏幕是 FeedScreen。
注册/登录/本地流程都运行良好。
问题:一旦用户成功登录,LoadingScreen 就会触发 API 调用,但 MainFlow 组件会在数据处于状态之前呈现。因为MainFlow中的组件需要数据,所以会报错。如何仅在数据存在后才呈现 FeedScreen 组件?
在LoadingScreen 中,我正在从上下文对象QuestionContext 触发对useEffect 的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;
getAllQuestions 是 QuestionContext 中的一个函数,它进行 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 调用成功,我可以看到响应存储在 state 中。但是,它会在此之前导航到 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?
【问题讨论】:
标签: reactjs react-native react-navigation render use-effect