【发布时间】: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