如何在react-native中重新渲染componenet?

问题描述

我是本机开发的新手,已经花了2天的时间解决此问题。我的打字不好,但是我可以用源代码解释问题。

当前情况:

  1. 应用程序的主屏幕: 有用于停靠特定卡的停靠图标。在单击扩展坞图标后,该卡作为扩展坞列表存储在数据库中。一切正常。

  2. 在主屏幕上,有诸如切换到Docklist之类的链接: 当我单击“ Docklist”时,它将在“ Docklist”屏幕上重定向,一切正常。

  3. 在DockList屏幕上,有4张卡,例如“卡a”,“查看底座列表”,“卡c”,“卡d”

在此屏幕上执行的步骤:

  1. componentDidMount()
    • 在componentDidMount()上,我正在从AsyncStorage(Local Storage)中获取“ ID”,并将该值设置为state。我将此ID传递给api参数。
    • 调用服务器API(this.viewDockList())

问题领域:

  • 根据我的知识和研究,componentDidMount()在渲染后仅被调用一次。
  • 当我随时单击“查看DockList”时,我需要调用api。
  • 在这里,当我刷新应用程序时,以下情况正在起作用
    1. 主屏幕->我从主屏幕停靠了卡

    2. 在主屏幕上->单击“切换到DockList”->导航到Dock屏幕

    3. 在Dock屏幕上->单击“查看Dock列表”->首次调用api并根据我的要求显示数据。

    4. 现在,我返回主屏幕,再次停靠卡,然后导航到停靠屏幕,然后单击查看停靠列表,那时Api并没有调用,只有render()正在调用在这里,我需要再次调用API并从服务器获取最新数据。我尝试在单击“查看停靠细节”时调用强制更新,调用了api,但列表未更新。

这是我的源代码

componentDidMount() {
    console.log("ComponentDidmount called")

    AsyncStorage.getItem('Id').then(value => {
        if (value !== null) {
            this.setState({ profileId: value })
        }
    })

    this.getDockedData();
}

 getDockedData = async () => {

    this.showLoading();

    console.log("API CALLED=====")

    try {
        let axiosConfig = {
            headers: {
                'Access-Control-Allow-Origin': '*'
            },params: {
                pId: this.state.profileId,}
        }

        axios.get('apiendpoint',axiosConfig)
            .then((res) => {

                this.setState({
                    sourceData: [...res.data.filter((item) => { if (!item.s_updated && !item.b_updated && !item.p_updated) return item })],});
                console.log("Data from dock api====",this.state.sourceData)
                this.hideLoading();
            })
            .catch((err) => {
                console.log("AXIOS ERROR WHILE GETTING DOCK DATA: ",err);
                this.hideLoading();
            })
    }

    catch (error) {
        console.log("ERROR======",error);
        this.hideLoading();
    }
}

   forceUpdate() {
    console.log("Force update called===")
    this.getDockedData();
  }   

//On render I am calling component 
 <Dockcomp  description="Lorum ipsum" onButtonPress={() => this.props.navigation.navigate('dockdetailscreen',{ item: sourceData,type: "docked",UpdateUI: this.UpdateUI },this.forceUpdate())} />

预期的响应:

  1. 主屏幕->我从主屏幕停靠了一张卡片
  2. 在主屏幕上->单击“切换到DockList”->导航到Dock屏幕
  3. 在Dock屏幕上->单击“查看Dock列表”->每当我单击“查看Dock列表”时,都应该调用api。现在只调用一次,因为我使用了componentDidMount()

非常感谢您!从过去的两天开始,我真的为此而苦苦挣扎。

解决方法

您不需要重新渲染。一旦使组件成为焦点,就可以编写一个侦听器来触发getDockedData。像这样的东西:

componentDidMount() {
    this.unsubscribe = navigation.addListener('focus',() => {
      // stuff you are already doing in componentDidmount
    });
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

您可以了解有关监听器和导航事件here

的更多信息 ,

React 和 React-Native 使用 shadowDOM 来评估何时触发重新渲染。除非强制,否则仅在组件的 stateprop 更改时才会重新渲染。在这一点上,在树中进行浅层比较以查看是否需要重新渲染。所以如果要调用重新渲染,可以在 componentDidMount 中添加一个触发状态更改的侦听器。或者其他任何地方。