Reactjs 反应警告:在构造期间未正确初始化状态

Reactjs 反应警告:在构造期间未正确初始化状态,reactjs,Reactjs,我使用react 16.3中的getDerivedStateFromProps。为什么react会显示此警告 在构造期间未正确初始化状态。状态应为对象,但未定义。 演示 类TestComponent扩展了React.PureComponent{ 静态getDerivedStateFromProps(下一步){ const{record,}=nextProps; 返回{ 标题:记录?记录。标题:“”, }; } render(){ const{title}=this.state; 返回( {tit

我使用react 16.3中的
getDerivedStateFromProps
。为什么react会显示此警告

在构造期间未正确初始化状态。状态应为对象,但未定义。

演示

类TestComponent扩展了React.PureComponent{ 静态getDerivedStateFromProps(下一步){ const{record,}=nextProps; 返回{ 标题:记录?记录。标题:“”, }; } render(){ const{title}=this.state; 返回( {title} ); } }
是的,您需要为状态设置初始值:

class TestComponent extends React.PureComponent {
  constructor(props) {
   super(props);
   this.state = {
    title: ''
   };
 }
// rest of your code
或者,使用:(如果您正在使用create react app创建应用程序,则支持此操作)


您可能有兴趣在介质上阅读此内容。

是的,您需要设置状态的初始值:

class TestComponent extends React.PureComponent {
  constructor(props) {
   super(props);
   this.state = {
    title: ''
   };
 }
// rest of your code
或者,使用:(如果您正在使用create react app创建应用程序,则支持此操作)


您可能有兴趣在媒体上阅读此内容。

我知道他们为什么这样做,但我可以看到,当组件不需要状态时,此问题会变得令人恼火。在对道具值进行试验后,
componentdiddupdate
不会收到与
getDerivedStateFromProps
相同的道具,因此如果后者成为获得最新道具的唯一可靠方法,则这意味着必须向以前不需要它的组件添加状态。我的代码没有任何状态,仍然得到警告。指导我解决它。@Goutham.T.J连接小提琴可能有助于调试。如果没有状态,就不应该有此错误。错误应该是其他的?@BhojendraNepal发生错误是因为react dom中的这一行:`if(typeof ctor.getDerivedStateFromProps==='function'&&state===null)`注意,如果使用redux并实现getDerivedStateFromProps,react组件中的状态可能为null。如果在组件的构造函数中将状态初始化为{},问题就会消失。我知道他们为什么这样做,但我可以看到,当组件不需要状态时,这个问题会变得很烦人。在对道具值进行试验后,
componentdiddupdate
不会收到与
getDerivedStateFromProps
相同的道具,因此如果后者成为获得最新道具的唯一可靠方法,则这意味着必须向以前不需要它的组件添加状态。我的代码没有任何状态,仍然得到警告。指导我解决它。@Goutham.T.J连接小提琴可能有助于调试。如果没有状态,就不应该有此错误。错误应该是其他的?@BhojendraNepal发生错误是因为react dom中的这一行:`if(typeof ctor.getDerivedStateFromProps==='function'&&state===null)`注意,如果使用redux并实现getDerivedStateFromProps,react组件中的状态可能为null。如果您在组件的构造函数中将状态初始化为{},问题就会消失。
class TestComponent extends React.PureComponent {
  state = {
   title: ''
  }
// rest of your code