我刚刚了解到componentWillReceiveProps
已被弃用,我们现在需要使用getDerivedStateFromProps
生命周期方法。https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
下面是我使用它的方法:
class Main extends Component {
static getDerivedStateFromProps(props) {
console.log('getDerivedStateFromProps', props);
const { modal } = props;
this.setState({ modal });
}
constructor(props) {
super(props);
this.state = {
modal: {}
};
}
然而,它在setState
上出错了
main.js:30未捕获TypeError:无法在getDerivedStateFromProps (main.js:30)读取null的属性“”setState“”
这里我漏掉了什么?
发布于 2018-06-01 04:51:57
因为getDerivedStateFromProps
是一个static
函数,所以没有实例(this
)。
相反,此函数的设计目的是让您返回状态,而不是使用this.setState
。
static getDerivedStateFromProps(props) {
console.log('getDerivedStateFromProps', props);
const { modal } = props;
return { modal };
}
发布于 2018-06-10 22:48:56
除了前面已经指出的错误(你需要返回状态),你的实现是错误的,不能正常工作。
您正在尝试将道具“同步”到本地状态。这不是一个好主意,因为父组件的任何不相关的重新渲染都会破坏本地状态。
看起来你应该完全移除getDerivedStateFromProps
,直接使用道具。在这个示例中,您根本不需要本地状态。
要更深入地了解为什么打破了这种模式,以及一些简单的替代方案,请查看 。
发布于 2018-06-01 04:52:19
您可以在静态方法的上下文中使用它。静态不依赖于类的实例,因此这是不同的。最好的方法是在非静态方法中返回modal,然后从那里设置它:D
class Main extends Component {
static getDerivedStateFromProps(props) {
console.log('getDerivedStateFromProps', props);
const { modal } = props;
return modal;
}
constructor(props) {
super(props);
this.state = {
modal: {}
};
SetModalState(modal)
{
this.setState(modal)
}
}
https://stackoverflow.com/questions/50632573
复制相似问题