【问题标题】:How to update title in react native render?如何在反应原生渲染中更新标题?
【发布时间】:2020-05-19 03:07:32
【问题描述】:

我有一个简单的函数:

render() {
    if (this.state.isLoading) {
        // this.props.navigation.setParams({
        //  title: 'Order: Loading'
        // });

        return(
            <View style={{
                flex: 1, 
                alignItems: 'center',
                justifyContent: 'center',
            }}>
                <ActivityIndicator/>
            </View>
        )
    }
}

问题是当我取消注释 this.props.navigation.setParams 时,我收到以下错误:Maximum update depth exceeded

你知道有什么解决办法吗?

【问题讨论】:

  • 在这里您正在设置渲染函数内部的状态由于在函数内部设置状态,您会收到错误最大更新深度超出。

标签: react-native react-navigation jsx react-navigation-stack


【解决方案1】:

我想说你采用的方法有点模糊,这就是为什么你在渲染中放置了 setparams,所以它无限循环。

我想你正在做一个 API 调用,根据 this.state.isLoading 依赖。所以现在,我要说的是最初将header 的标题设置为Is Loading.

constructor(props){
this.state={
isLoading:true,
title:'Is Loading'
}
}

现在假设您进行了一次 api 调用并得到了结果:

like fetchApiData = async() => {

axios.post(url).then((data) => {

this.setState({isLoading:false,title:data.title});
this.props.navigation.setParams({
         title: data.title
        });

}).catch(err => {
this.setState({isLoading:false,title:error});
this.props.navigation.setParams({
         title: error
        });

})

希望你清楚。感觉 。解惑

【讨论】:

    【解决方案2】:

    这是我的解决方案。使用此代码更新您的navigationOptions

    static navigationOptions = ({ navigation }) => ({
      headerTitle: navigation.state.params.title || <View style={{ justifyContent: 'center', alignItems: 'center', flex: 1 }}><ActivityIndicator size="small" color="#ffffff" /></View>
    });
    

    上面的代码将显示加载指示器(或者您可以设置静态加载文本),直到它没有得到参数title。现在,在获取您的订单后设置此 title 参数,如下所示:

    fetchOrders = () => {
      const order = await fetchOrders(); // your code to fetch orders
      this.props.navigation.setParams({ title: (order) ? order.title : "UNTITILED" });
    
      // Note : Always check if order is available or not to avoid unexpected error
    }
    

    如果你使用它,不要忘记从 react-native 导入 ActivityIndicator

    【讨论】:

      【解决方案3】:

      您应该为此使用componentDidUpdate

      componentDidUpdate(prevProps, prevState) {
        if (this.state.loading) {
          this.props.navigation.setParams({
            title: 'Order: Loading'
          });
        }
      }
      

      【讨论】:

      • ComponentDidUpdate 在每次更改时运行,因此您不能直接在 componentDidUpdate 函数中设置状态。
      猜你喜欢
      • 2019-07-31
      • 2021-12-28
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 2022-11-07
      • 2020-11-15
      • 1970-01-01
      相关资源
      最近更新 更多