I'm trying to update a component via a different component. My update includes a simple AJAX code. My update is triggered using a Redux state change (simple boolean switch). My code looks like this (a bit simplified):
ComponentA (triggering the update):
update=()=>{
const {updateComp} = this.props; //Redux action
updateComp();
}
render(){
return(
<Reactstrap.Button type="submit" form="postform" onClick={()=>{this.close(), this.update();}}>Update</Reactstrap.Button>
);
}
ComponentB (calling the update using AJAX):
updateFromServer=(data)=>{
const {updateComp} = this.props;
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200){
data = this.responseText;
}
}
xhttp.open("GET", '/fetch', true);
xhttp.send();
updateComp(); //Triggering the Warning
}
handleUpdate=()=>{
const {update} = this.props;
if(update){
this.state = {tweets: []};
this.updateFromServer(this.state.tweets);
}
}
render(){
this.handleUpdate();
....
}
Which gives me the Warning:
Cannot update a component (`Connect(ComponentB)`) while rendering a different component (`ComponentB`)
And the stack points to the line in ComponentB where updateComp()
is called.
Now I've searched throughout the web and every solution I see talks about using useEffect
, but I'm using a class-based components and don't have hooks so that solution is of no use to me.
Any other option to solve this issue other than useEffect
?
question from:
https://stackoverflow.com/questions/65918549/cannot-update-a-component-connectcomponent-warning-with-redux-state-change 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…