【问题标题】:React componentDidMount not called on component reload在组件重新加载时未调用 React componentDidMount
【发布时间】:2020-01-20 02:33:58
【问题描述】:

我有一个数据表列表。在数据表中,我有一些设备的数据每当我单击 ID 时,我都会打开一个侧边栏,其中显示一些数据。 我面临的问题是第一次调用 api 时单击 ID 获取数据并正确显示。但是,当我再次单击 ID 时关闭侧边栏后,它不会加载任何内容(不调用 API)。

我无法为此创建代码笔,但以下是我的代码。

我的代码 -

onCLick ID -

_onClickCompliance(deviceId);

const _onClickCompliance = deviceId => {
    ReactDOM.render(
        <ComplianceDetails deviceId={deviceId} />,
        document.getElementById("ComplianceDetailsModalDiv")
    );
};

在 ComplianceDetails 组件中 - 第一次 onClick 它进入 componentDidMount 但再次点击它不是。这就是为什么我为此设置了componentDidUpdate。如果我删除这个componentDidUpdate,它总是在表中的ID onCLick 之后加载侧边栏中的旧数据。

`getDetailsByDeviceID` this is called to get the data from API and sets value in state

我的代码 -

    componentWillReceiveProps() {
        this.setState({ sideBarShow: true });
    }

    componentDidMount = () => {
        this.getDetailsByDeviceID();
    };

    componentDidUpdate(prevProps) {
        if (this.props.deviceId !== prevProps.deviceId) {
            this.getDetailsByDeviceID();
        }
    }

getDetailsByDeviceID 代码 -

getDetailsByDeviceID = () => {
        try {
            this._getComplianceDetailsApi(); //apis
        } catch (err) {
            toast({
                message: err,
                flavor: "error",
                options: { isHtml: true }
            });
        }
    };

如果我删除它,它会无限期地调用页面。

if (this.props.deviceId !== prevProps.deviceId)

我必须打电话给componentWillUnmount()吗?请指导我。

如果我不清楚,请告诉我。谢谢。

【问题讨论】:

  • 我的假设是,getDetailsByDeviceID 获取数据并设置为状态。由于此组件被重新渲染,因此将调用componentDidUpdate。你应该看看shouldComponentUpdate
  • yes rajesh,getDetailsByDeviceID 获取数据并设置为状态,让我检查一下 shouldCOmponentUPdate 谢谢
  • 只是一个指针,如果您使用最新的反应,请查看 useEffect 钩子。那仍然会执行无限循环,但冗余代码会更少
  • 是的,我最近更新了 react 最新版本,但我的代码使用的是 react 版本的旧 sn-ps,如果可能的话,你能指出我可以改变什么并解决这个问题吗?
  • 请分享“getDetailsByDeviceID”的代码。

标签: javascript reactjs


【解决方案1】:

如果您希望在 deviceId 更改时重新挂载您的组件,您可以使用 ComplianceDetails 上的 key 属性,如下所示:

<ComplianceDetails key={deviceId} deviceId={deviceId} />

【讨论】:

  • 问题仍然存在,任何其他解决方案。
  • 嗨,你有解决这个问题的办法吗?
猜你喜欢
  • 2020-04-27
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 2023-03-03
  • 2019-08-16
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多