react: uncaught TypeError: Cannot read property 'state' of undefined

react: uncaught TypeError: Cannot read property 'state' of undefined

我正在尝试从 General class 中获取函数 Application 中的 'state' 对象,但出现此错误 "Uncaught TypeError: Cannot read property 'state' of undefined"。 密码是

class General extends Comment {
  constructor() {
    super();
    this.state = { comments: first_comment};
  }
}

const Application = () => {
  return (
    <div> Hello world beginner: {this.state.comments}</div>
  );
};

render(<Application/>, document.getElementById('container'));

应用程序是无状态组件。并不是说箭头函数具有上下文的词法范围。

为无状态组件使用 props。

const Application = (props) => {
  return (
    <div> Hello world beginner: {props.comments}</div>
  );
};

或扩展React.Component

class Application extends React.Component {
  constructor() {
     // init state
  }

  render() {
    return <div> Hello world beginner: {this.state.comments}</div>
  }
}

几件事:

*Stateless Functional Components 没有 statelifecycle 方法和 this 关键字。

*您需要连接 GeneralApplication 组件,以便 Application 组件可以使用 state 通用值 component.

*将 Application 组件作为 General 组件的子组件,并在 props 中传递注释值,并在 Application 中通过 props.comments.[=26 访问该值=]

这样写:

class General extends Component {
  constructor() {
    super();
    this.state = { comments: first_comment};
  }
  render(){
     return (
        <div>
            <Application comments={this.state.comments}/>
        </div>
     )
  }
}

const Application = (props) => {
  return (
    <div> Hello world beginner: {props.comments}</div>
  );
};

render(<General/>, document.getElementById('container'));

检查工作示例:

class General extends React.Component {
      constructor() {
        super();
        this.state = { comments: 'first_comment'};
      }
      render(){
         return (
            <div>
                <Application comments={this.state.comments}/>
            </div>
         )
      }
    }
    
    const Application = (props) => {
      return (
        <div> Hello world beginner: {props.comments}</div>
      );
    };
    
    ReactDOM.render(<General/>, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container'/>

在您的 class 组件中,您应该扩展或子classing React.Component 并且当您这样做时,这意味着您将覆盖 constructor() 功能React.Component classes 与来自 General class 组件的那个,但你不想这样做,你仍然想访问 React.Component constructor() 所以你需要将 props 传递给构造函数和 super().

接下来,当将状态作为 props 传递给功能组件时,您需要将 props 作为参数传递给功能组件,否则在这样做时例如:

import React from 'react';

const ImageList = () => {
  console.log(props.images);
  return <div>ImageList</div>;
};

export default ImageList;

你会得到同样的错误。想象一下,我正在尝试从基于 General class 的组件访问状态到上面的这个 ImageList 组件中,我确实将它导入到 General,它会给我同样的结果错误,因为我没有将 props 作为参数传递给 ImageList 功能组件。