我使用getDerivedStateFromProps
作出反应16.3。为什么反应会显示此警告?
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>
);
}
}
答案 0 :(得分:8)
是的,您需要为州设置初始值:
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
您可能有兴趣在媒介上阅读此blog。