Solution for React not refreshing subcomponents after SetState

problem
//Negative teaching material. If you don't know why, don't write like this //Reminder again: if you don't know why to write the negative textbook, don't write it like this class A extends React.Component{ constructor(props){ super(props); this.state = { test:"t1"; } } render(){ return( <div> <B testVal={this.state.test} /> //Other codes, etc </div> ) } someCallBackFunc(str){ this.setState({ test:str }) } } class B extends React.Component{ constructor(props){ super(props); //Remind me again: if you don't know what you are writing, don't write negative textbooks this.state = { //In addition to special needs, copying props into state should be avoided as far as possible. testVal:this.props.testVal; } } render(){ return( <div>{this.state.testVal}</div> ) } }
reason
Avoid copying props into state! The problem is that it’s both unnecessary (you can use this.props.color directly instead), and creates bugs (updates to the color prop won’t be reflected in the state). Only use this pattern if you intentionally want to ignore prop updates. In that case, it makes sense to rename the prop to be called initialColor or defaultColor. You can then force a component to “reset” its internal state by changing its key when necessary.
resolvent
-
Direct use this.props.testVal
Modify the Render content of B to: render(){ return( <div>{this.props.testVal}</div> ) } -
Rewrite props change callback (not recommended)
Override method in B componentWillReceiveProps : componentWillReceiveProps(nextProps){ this.setState({ testVal:nextProps.testVal }); } This method will be called when props change, and the state can be updated at this time.