首页 > 解决方案 > 如何在 react-native 中重新渲染组件?

问题描述

我是 react-native 开发的新手,已经为这个问题花了 2 天时间。我不擅长打字,但我可以用我的源代码解释问题。

当前情景:

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

  2. 在主屏幕上有诸如切换到 Docklist 之类的链接:当我单击停靠列表时,它将重定向到停靠列表屏幕上,它工作正常。

  3. 在 DockList 屏幕上有 4 张卡片,例如“Card a”、“查看停靠列表”、“Card c”、“Card d”

在此屏幕上执行的步骤:

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

问题领域:

这是我的源代码:

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 Screen -> 点击“View Dock List” -> 每当我点击 View Dock list 时,应该调用 api。现在它只调用一次,因为我使用了 componentDidMount()

非常感谢您!我真的在过去两天为这个问题苦苦挣扎。

标签: react-nativecomponentsreact-lifecycle

解决方案


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


推荐阅读