渲染函数中的setState()返回?

时间:2018-11-13 21:28:52

标签: react-native state render react-native-android

this.state = {
      fontLoading: false,
      dataFetched: false,
    };

我有两种状态,即异步组件内部的fontloading正在更改,而另一个函数内部的dataFetched正在更改。 “ fontLoading”正在以下功能中更改。

async componentDidMount () {
    try {
      await Font.loadAsync ({
       ...
      });
      this.setState ({fontLoading: true});
    } catch (error) {
      ...
    }
}

如果if和else可以很好地与fontLoading和dataFetched一起使用,则可以。最后,条件屏幕被渲染了一秒钟,但出现错误,因为单击按钮时我试图更改dataFatched状态。一秒钟后,Render函数再次在“ else if”条件下渲​​染View。但是我想渲染其他条件,当我单击按钮时,如果返回,我必须获取其他条件。

render(){
    if (!this.state.fontLoading) {
      return (<ActivityIndicator />);
    }
    else if (!this.state.dataFetched) {
      return (new<View>)
    }
    else {
      return (
      <View>
        <Button title = 'Click' onPress={this.setState({dataFetched: false});}></Button>
      </View>
     );
    }

我对渲染函数内部的设置状态不了解。我应该怎么做才能完成这项特定任务?在这里学习这一点将增加我的学习流程,因为在具有状态变化的同一个组件内部进行渲染既鼓励了如何使用状态,又使我想让反应本色变得美丽。

1 个答案:

答案 0 :(得分:1)

呈现onPress属性的方式最终将在呈现组件时立即调用this.setState({dataFetched: false})。应该为onPress提供一个函数作为参数,并且该函数应调用setState

onPress={this.setState({dataFetched: false});} // <- Replace this

onPress={() => this.setState({dataFetched: false})} // <- with this
相关问题