S.M*_*ian 4 javascript reactjs
在componentWillReceiveProps函数内部我调用了另一个函数:
componentWillReceiveProps(nextProps){
if(nextProps.cart){
var cart = nextProps.cart;
this.setState({cart:cart,
offCart:cartHelper.getOffCart(cart),
totalPay:cartHelper.getTotalPayCart(cart)});
this.useFinance()//at this line makes this error
}
useFinance(){
if(this.state.useFinance)
{
this.setState({useFinance:false})
}else{
if(this.state.totalPay > this.state.user.user.finance)
{
this.setState({useFinance:false})
}else{
this.setState({useFinance:true})
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用react-redux,我应该useFinance在购物车更新时调用函数。
我收到此错误消息:
warning.js?8a56:33 Warning: performUpdateIfNecessary: Unexpected batch number (current 2, pending 1)
Run Code Online (Sandbox Code Playgroud)
componentWillReceiveProps如果值仍然相同,则不要每次都调用 setState 。检查从nextprops内部接收的值和实际值,state如果它们不相等,则调用setState.
componentWillReceiveProps(nextProps) {
if (nextProps.cart && nextProps.cart != this.props.cart) { //Do this in case of object => JSON.stringify(nextProps.cart) != JSON.stringify(this.props.cart)
var cart = nextProps.cart;
this.setState({
cart: cart,
offCart: cartHelper.getOffCart(cart),
totalPay: cartHelper.getTotalPayCart(cart)
});
this.useFinance() //at this line makes this error
}
}
useFinance() {
if (this.state.useFinance) {
this.setState({
useFinance: false
})
} else {
if (!(this.state.totalPay > this.state.user.user.finance)) {
this.setState({
useFinance: true
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
我会尝试执行单个setState更新,例如:
componentWillReceiveProps(nextProps){
if(nextProps.cart){
var cart = nextProps.cart;
const useFinance = !this.state.useFinance || (this.state.totalPay <= this.state.user.user.finance)
this.setState({
useFinance,
cart: cart,
offCart: cartHelper.getOffCart(cart),
totalPay: cartHelper.getTotalPayCart(cart)
});
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这可能会导致无限更新,因为您
更新状态 -> componentWillRecieveProps -> 更新状态 -> componentWillReceiveProps ...
这就是为什么您需要检查是否需要更新:
componentWillReceiveProps(nextProps){
if(this.doWeNeedAnUpdate(this.props, nextProps)){
...
}
}
Run Code Online (Sandbox Code Playgroud)