reactjs - 错误:无法对未安装的组件执行 React 状态更新。这是一个无操作,但它表明您的应用程序中存在内存泄漏
问题描述
我收到上述错误,我不知道如何处理它。
我有一个组件。在 render() 中,我循环遍历一个数组并放置另一个组件并将值解析为该组件,如下所示:
render() {
let allProducts = this.state.products.map((product, i) => {
return (
<div key={product.article}>
...
<PriceStock value={product.article} />
...
</div>
)
})
}
在 PriceStock 组件中,我使用 axios 获取一些数据,如下面的代码:
export default class PriceStock extends React.Component {
constructor(props) {
super(props);
this.state = ({
buttoprice: ''
})
this.getPriceAndStock = this.getPriceAndStock.bind(this)
}
getPriceAndStock(articleNo) {
return axios.post('LINK_TO_URL', {
articleNo: articleNo
}).then(result => {
return result.data
})
}
async componentDidMount() {
let pricestock;
pricestock = await this.getPriceAndStock(this.props.value)
let bruttoPrice = PRICE_TO_PARSE_TO_THE_STATE;
this.setState({ buttoprice: bruttoPrice })
}
render() {
return (
<div >
{this.state.buttoprice}
</div>
);
}
}
当我尝试在 componentDidMount 中设置状态时,错误似乎发生了,有什么建议吗?
解决方案
这是一个错误,因为您在初始化之前更新状态 在构造函数中执行加载活动这是正确的方法
getPriceAndStock(orderNumber, articleNo) {
return axios.post('LINK_TO_URL', {
orderNr: orderNumber, vareNr: articleNo
}).then(result => {
return result.data
})
}
constructor() {
this.getPriceAndStock(this.props.value)
.then(pricestock=>{
let bruttoPrice = PRICE_TO_PARSE_TO_THE_STATE;
this.state({ buttoprice: bruttoPrice })
})
.catch(console.log)
}
推荐阅读
- git - 为什么 `git branch -D SomeOtherBranch` 删除了我当前分支上的文件?
- django - 从 Lambda Django 连接到 Aurora Serverless?
- pandas - 具有多级列的熊猫数据框中的数据透视表
- fetch - 如何使用 Svelte/Sapper 在 fetch/preload 中包含凭据?
- javascript - 用javascript多次附加一个带有参数的html模板
- java - 检查值时使用 Hibernate 的 DB2 查询问题
- css - 带装饰的 CSS Drop Cap
- node.js - 使用 Google Maps API 进行反向地理编码的 Axios 块请求
- amazon-web-services - Deepracer log_analysis 工具 - sagemaker 角色错误
- jquery - Bootstrap 4折叠过渡不适用于col-2类