Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

javascript - Reactjs: setstate rendering order problem

i'm new using reactjs. I'm using a Select element with onChange handle. I save the selected value with setState: productFilterChosenValue. Then with handleClick on my button "onClick" event, i do the

this.setState({
  productFilterChosenValue: this.state.productFilterValue,
});

So i have productFilterChoseValue updating his value only on click with the current Select value. And it works fine, because if in my render() function i put {this.state.productFilterValue} then it will show value changing only on button click.

But if I add a component (my own component) in the bottom, giving it as prop the same value

<FetchedTableGrid
     apiRoute={
       this.state.productFilterChosenValue
     }
/>

It will update only after 2 clicks. So I have my value printed and working correctly and the same value as prop that changes state on second click.

Inside my FetchedTableGrid component, I have put console.log(this.props); trying componentDidMount and componentWillReceiveProps getting same error. If I use componentWillUpdate or componentDidUpdate it gets infinity looped.

question from:https://stackoverflow.com/questions/65933731/reactjs-setstate-rendering-order-problem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can not do it this way. The problem is, that if you set the state, then the state updates and since the setState function depends explicitly on the state it get's recalled. Hence an infinite loop.

What you have to do, is passing the previous value as an input to setState:

this.setState((prevState) => ({
  productFilterChosenValue: prevState.productFilterValue,
}));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...