reactjs - REACT JS 类生命周期:如何将 http 请求放入 ComponentdidUpdate?
问题描述
一旦prop
从 redux 商店更新,我有一个 http 请求要调用,如下所示:
const mapStateToProps = state => {
console.log(state.queryBuild);
return {
queryBuilderObject: state.queryBuild,
}
}
export default connect(mapStateToProps, null)(SummaryView);
这是我的componentdidupdate
功能:
async componentDidUpdate()
{
//console.log("Component unmount detected");
//console.log(this.props.queryBuilderObject);
this.setState({state: {
...this.state,
isLoading: true,
}});
await axios.post(ApiEndPoints.getSummaryDataByQueryBuilder,this.props.queryBuilderObject,{timeout: axiosTimeOut})
.then(response => {
console.log("REsponse:");
console.log(response);
this.setState({state: {
...this.state,
isLoading: false,
}});
})
.catch(error => console.log("Error: " + error.message));
}
props.queryBuilderObject
现在这是问题所在......不知何故,如果来自 redux 商店的更改,我只想发出一个 http 请求。但是当我这样做时,我在设置状态时进入了一个无限循环,因此每次都会触发 componentdidupdate。
有人可以建议这样做的正确方法吗?
解决方案
componentDidUpdate
接收先前的道具和状态作为参数,您可以检查先前的道具'queryBuilderObject
与当前道具' queryBuilderObject
,如果它们不相等,则执行 POST 请求。
componentDidUpdate(prevProps, prevState, 快照)
您可以
setState()
立即调用,componentDidUpdate()
但请注意它必须包含在一个条件中
如果您在没有条件检查的情况下从此生命周期函数更新状态,则可能会导致无限渲染循环。
也不需要在setState
函数中以现有状态进行传播;setState
对状态更新进行浅合并。
async componentDidUpdate(prevProps) {
if (prevProps.queryBuilderObject !== this.props.queryBuilderObject) {
this.setState({ isLoading: true });
await axios
.post(
ApiEndPoints.getSummaryDataByQueryBuilder,
this.props.queryBuilderObject,
{ timeout: axiosTimeOut }
)
.then((response) => {
this.setState({ isLoading: false });
})
.catch((error) => console.log("Error: " + error.message));
}
}
推荐阅读
- amazon-dynamodb - 插入删除、dynamoDb 并检查 SpringBoot
- python - 使用 Python 查询页面对象模型
- asynchronous - 等到 openlayers 5 geolocation 返回一个值
- php - 有人可以向我解释一下这个 php 数组中的“\”是做什么的吗?
- json - 使用 powershell 正确格式化 json dict 对象
- c# - ASP.net mvc API 获取请求和 JSON 数据
- javascript - Mailto 链接垃圾邮件防护
- sql - 累计金额不低于零
- scala - Spark Dataframe - 显示每列的空行数
- sql-server - 将数据库复制到现有数据库的脚本