为什么 setState 不重新渲染应用程序?

时间:2021-07-18 22:56:46

标签: reactjs react-native

我正在尝试使用 React Native 中的 Text 组件显示存储在内存中的值。存储和读取工作正常,我可以在控制台中获得正确的值。我获取值并使用它们设置状态。

getData = async (key) => {
try {
  const value = await AsyncStorage.getItem("@"+key);
  return value != null ? JSON.parse(value) : null;
} catch(e) {
  // error screen
}
}

// ... some code here (btw its all inside of the class App)

fetchData = async () => {
this.setState({
  role: await this.getData("role"),
  calls_version: await this.getData("v_calls")
});
}

_ = this.fetchData();  // calling this to run fetchData function

splashScreen = () => {
return (
  <View style={ styles.splash_screen }>
    <Image style={ styles.splash_image } source={{ uri: "..." }}/>
    <Text style={ styles.splash_text }>{ this.state.role }</Text>
  </View>
);
}

render() {
return (
  <NavigationContainer>
    <Stack.Navigator>
      <Stack.Screen options={{headerShown: false}} name="Splash" component={ this.splashScreen } />
    </Stack.Navigator>
  </NavigationContainer>
);
}

但是当我运行它时,什么也没有发生。 如果这有帮助,这里是 this.state.role 值的顺序:

  1. render() 中未定义
  2. 在 splashScreen() 中未定义
  3. render() 中的“正确值”
  4. fetchData() 完成

提前致谢。

0 个答案:

没有答案