Reputation: 77
import React,{ Component } from 'react';
import { connect } from 'react-redux';
import { itemid } from '../actions/action';
class DetailPage extends Component{
componentWillUpdate(){
this.props.dispatch(itemid([this.props.params.item,`${this.props.params.item}${this.props.params.id}`]))
}
render(){
const { dispatch } = this.props;
return(
<div>
{this.props.params.id}
</div>
)
}
}
function selectstate(state){
return{
state
}
}
export default connect(selectstate)(DetailPage)
// {this.props.params.item} are from react-router (path('/detail/item/id'))
why my dispatch are Infinite loop until error (Maximum call stack size exceeded)
Upvotes: 3
Views: 3090
Reputation: 1070
You're firing dispatch on componentWillUpdate
. So every time you update state, you're updating state again. You should never modify state in componentWillUpdate: https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate
Incidentally, doing this in componentWillReceiveProps
will likely do the same thing, since your state, from the redux store, will come in as props
.
The question is why are you doing the dispatch after updating? Is it because of the function setting state below?
If you're looking to dispatch after setting a particular state, then you can prevent updates except in that state using shouldComponentUpdate
. But that feels like a side effect in this configuration. I think you're much better off dispatching your event at the same time as you set state, or as a callback to that.
Upvotes: 3