【问题标题】:setState() in render function return?渲染函数中的setState()返回?
【发布时间】:2019-04-16 19:16:34
【问题描述】:
this.state = {
      fontLoading: false,
      dataFetched: false,
    };

我有两个状态,字体加载在异步 componentDidMount() 内部发生变化,而 dataFetched 在另一个函数内部发生变化。 'fontLoading' 在下面的函数中发生变化。

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

首先 if 和 else if 可以正常使用 fontLoading 和 dataFetched。在最后一个其他条件屏幕呈现一秒钟,而不是我得到一个错误,因为我试图在单击 Button 时更改 dataFatched 状态。渲染函数在一秒钟后再次在“else if”条件下渲​​染视图。但是我想渲染 else 条件,当我单击按钮时,如果返回,我必须得到 else 。

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>
     );
    }

我对在渲染函数中设置状态没有一定的了解。我应该怎么做才能完成这个特定的任务?在这里学习这一点将增加我的学习流程,因为在具有状态更改的同一组件内进行渲染既鼓励了如何使用状态,也鼓励了我想是什么让 react-native 变得漂亮。

【问题讨论】:

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


    【解决方案1】:

    编写onPress 属性的方式最终会在渲染组件时立即调用this.setState({dataFetched: false})onPress 应该被赋予一个函数作为参数,并且该函数应该调用 setState

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

    【讨论】:

    • 感谢您的快速回复@Eugene Pawlik。它有效。
    猜你喜欢
    • 2023-04-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    相关资源
    最近更新 更多