React getDerivedStateFromProps() 方法
getDerivedStateFromProps() 方法格式如下:
static getDerivedStateFromProps(props, state)
getDerivedStateFromProps 会在调用 render 方法之前调用,即在渲染 DOM 元素之前会调用,并且在初始挂载及后续更新时都会被调用。
state 的值在任何时候都取决于 props。
getDerivedStateFromProps 的存在只有一个目的:让组件在 props 变化时更新 state。
该方法返回一个对象用于更新 state,如果返回 null 则不更新任何内容。
以下实例 favoritesite 的初始值为 zhishitu,但是 getDerivedStateFromProps() 方法通过favsite 属性更新了 favoritesite 的值:
实例 class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritesite: "zhishitu"};
}
static getDerivedStateFromProps(props, state) {
return {favoritesite: props.favsite };
}
render() {
return (
<h1>我喜欢的网站是 {this.state.favoritesite}</h1>
);
}
}
ReactDOM.render(<Header favsite="Google"/>, document.getElementById('root'));
知识兔 » 实例 class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritesite: "zhishitu"};
}
static getDerivedStateFromProps(props, state) {
return {favoritesite: props.favsite };
}
changeSite = () => {
this.setState({favoritesite: "google"});
}
render() {
return (
<div>
<h1>我喜欢的网站是 {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeSite}>修改网站名</button>
</div>
);
}
}
ReactDOM.render(<Header favcol="taobao"/>, document.getElementById('root'));
知识兔 »
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritesite: "zhishitu"};
}
static getDerivedStateFromProps(props, state) {
return {favoritesite: props.favsite };
}
render() {
return (
<h1>我喜欢的网站是 {this.state.favoritesite}</h1>
);
}
}
ReactDOM.render(<Header favsite="Google"/>, document.getElementById('root'));
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritesite: "zhishitu"};
}
static getDerivedStateFromProps(props, state) {
return {favoritesite: props.favsite };
}
changeSite = () => {
this.setState({favoritesite: "google"});
}
render() {
return (
<div>
<h1>我喜欢的网站是 {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeSite}>修改网站名</button>
</div>
);
}
}
ReactDOM.render(<Header favcol="taobao"/>, document.getElementById('root'));
知识兔 »