【问题标题】:asynchronous function in render() method fails (Invariant Violation)render() 方法中的异步函数失败(不变违规)
【发布时间】:2019-10-26 20:38:18
【问题描述】:

我正在尝试在 render() 中使用异步函数:

 async _check() {
 const token = await AsyncStorage.getItem('myToken');
 if(token !== null) {
   this.props.navigation.navigate('My Screen', {token: token});
 }   
 else {
   return (
     <View style={styles.content_container}>
      ... 
     </View>
   );  
 }   
}


render() {
 return (
   <View>
     { this._check() }
   </View>
 );
}

但我收到此错误:
Invariant Violation: Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.

谁能告诉我我的代码有什么问题?

【问题讨论】:

    标签: react-native async-await


    【解决方案1】:

    您不能在渲染中使用任何异步函数或执行任何副作用(如导航)。这直接违反了 React 原则。渲染应该只从道具和状态渲染元素。除此之外,你得到的错误是因为你正在渲染异步函数的结果,它总是一个Promise。此外,在每次渲染时从 AsyncStorage 获取令牌没有意义,因为渲染会经常发生,最多每秒几次

    将您的逻辑放入lifecycle methods,例如componentDidMount,然后使用this.setState 以您想要的方式更改状态,并使用this.staterender() 中渲染您的组件

    class SomeComponent extends Component {
      constructor(props) {
        super(props)
        this.state = {
          message: ''
        }
      }
    
      async componentDidMount() {
        const token = await AsyncStorage.getItem('myToken')
        if (token !== null) {
          this.props.navigation.navigate('My Screen', { token: token })
        } else {
          this.setState({ message: 'token is missing' })
        }
      }
    
      render() {
        return (
          <View style={styles.content_container}>
            <Text>{this.state.message}</Text>
          </View>
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2017-11-05
      相关资源
      最近更新 更多