我收到上述错误,我不知道如何处理。
我有一个组件。在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中的setState时出现错误,有任何建议吗?
答案 0 :(得分:0)
这是一个错误,因为您在初始化状态之前正在更新状态 在构造函数中执行加载活动,这是正确的方法
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)
}
答案 1 :(得分:0)
在以下问题中找到了answear:https://github.com/material-components/material-components-web-react/issues/434
这让我想起了有关另一个stackoverflow问题的评论。