我使用来自react 16.3的getDerivedStateFromProps
。为什么react会显示此警告?
Did not properly initialize state during construction. Expected state to be an object, but it was undefined.
codepen上的演示
class TestComponent extends React.PureComponent {
static getDerivedStateFromProps(nextProps) {
const {record,} = nextProps;
return {
title: record ? record.title : '',
};
}
render() {
const {title} = this.state;
return (
<div>{title}</div>
);
}
}
发布于 2018-04-20 19:34:43
可以,您需要设置状态的初始值:
class TestComponent extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
title: ''
};
}
// rest of your code
或者,使用ES7 syntax:(如果您正在使用create-react-app创建应用程序,则将支持此功能)
class TestComponent extends React.PureComponent {
state = {
title: ''
}
// rest of your code
你可能会对medium上的这篇blog感兴趣。
https://stackoverflow.com/questions/49940677
复制相似问题