import React, { Component } from "react";
export interface MyComponentProps {
show: boolean;
}
export interface MyComponentState {
show: boolean;
}
export default class App extends Component<MyComponentProps, MyComponentState> {
static defaultProps = {
show: true
};
static getDerivedStateFromProps(props: MyComponentProps) {
console.log("getDerivedStateFromProps: ", props);
if ("show" in props) {
return { show: props.show };
}
return null;
}
constructor(props: MyComponentProps) {
super(props);
this.state = {
show: props.show
};
}
onClick() {
this.setState({ show: false });
}
render() {
const { show } = this.state;
return (
<div>
{show ? "teresa teng" : ""}
<button type="button" onClick={() => this.onClick()}>
toggle
</button>
</div>
);
}
}将在setState()之后执行getDerivedStateFromProps()静态方法。因此,我单击该按钮,尝试将state.show的值更改为false,但getDerivedStateFromProps()方法会将state.show更改为true。因此文本将始终可见。
getDerivedStateFromProps打算使用由父组件传入的属性来更新状态。
我该如何解决这个问题呢?游乐场codesandbox。
发布于 2021-03-18 19:28:19
getDerviedStateFromProps必然会在每次属性和状态更改后运行。这不是一个实际的设计,但这种功能上的变化是在React版本16.4中引入的(如果我没记错的话)。
现在,如果你想根据你的道具更新本地节目,也就是你的状态,你可以:
show,然后使用新的prop值。(正如@jonrsharpe在注释中提到的那样)。key属性,它会告诉你的组件在密钥改变的情况下完全卸载并挂载它自己。这将导致状态根据属性的值进行重置。对于ex来说,
<App show={this.state.show}
key={this.state.show}/>https://stackoverflow.com/questions/66689223
复制相似问题