React getDerivedStateFromProps () method


Release date:2024-03-13 Update date:2024-03-15 Editor:admin View counts:56

Label:

React getDerivedStateFromProps () method

getDerivedStateFromProps() the format of the method is as follows:

static getDerivedStateFromProps(props, state)

getDerivedStateFromProps will be called render method, that is, before rendering the DOM element, and during the initial mount and subsequent updates.

state at all times depends on props .

getDerivedStateFromProps exists for only one purpose: to make the component in the props update when Chan state .

This method returns an object for updating state if you return null nothing is updated.

The following example favoritesite the initial value of the runoob , but getDerivedStateFromProps() methods pass through favsite properties have been updated favoritesite walue of:

Example

classHeaderextendsReact.Component{constructor(props){super(props);this.state={favoritesite:"runoob"};}staticgetDerivedStateFromProps(props,state){return{favoritesite:props.favsite};}render(){return(<h1>My favorite website is{this.state.favoritesite}</h1>);}}ReactDOM.render(<Headerfavsite="Google"/>,document.getElementById('root'));

Example

classHeaderextendsReact.Component{constructor(props){super(props);this.state={favoritesite:"runoob"};}staticgetDerivedStateFromProps(props,state){return{favoritesite:props.favsite};}changeSite=()=>{this.setState({favoritesite:"google"});}render(){return(<div>
<h1>My favorite website is{this.state.favoritesite}</h1>
<buttontype="button"onClick={this.changeSite}>Change website name</button>
</div>);}}ReactDOM.render(<Headerfavcol="taobao"/>,document.getElementById('root'));

Powered by TorCMS (https://github.com/bukun/TorCMS).