简体   繁体   English

this.setState is not a function 错误仍然存在,即使我遵循了许多使用相同代码的示例

[英]this.setState is not a function error is persistent even though I have followed many examples that use the same code

I am new to React, and am trying to fill my components state with data stored on my mongodb Database.我是 React 新手,我正在尝试用存储在我的 mongodb 数据库中的数据填充我的组件 state。

I am using this call to fetch my data:我正在使用此调用来获取我的数据:

class DisplayPrograms extends Component {
  constructor(props) {
    super(props);
    this.setState = { programs: [] };
  }

  componentDidMount() {
    axios
      .get("http://localhost:5000/programs")
      .then((response) => {
        console.log(response.data);
        this.setState({ programs: response.data });
      })
      .catch(function (error) {
        console.log(error);
      });
  }

render() { .....

My render() function (not included) is working, and my console.log(response.data) outputs an array of objects like it is supposed to as you can see below, but I keep getting the following error:我的 render() function (不包括)正在工作,我的 console.log(response.data) 输出一个对象数组,如下所示,但我不断收到以下错误:

Array [ {…}, {…} ]
DisplayProducts.jsx:15
_________________________________________________

TypeError: "this.setState is not a function"
    componentDidMount DisplayProducts.jsx:16
DisplayProducts.jsx:19

I'm sure it's a quick fix but I haven't been able to find a solution.我确定这是一个快速修复,但我一直无法找到解决方案。

Your constructor should look like this:您的构造函数应如下所示:

  constructor(props) {
    super(props);
    this.state = { programs: [] };
  }

You were using this.setState() in the constructor instead of this.state Here are the docs on this which show the syntax.您在构造函数中使用this.setState()而不是this.state以下是显示语法的文档。

In constructor you need to create the initial state, so you need something like:constructor中,您需要创建初始 state,因此您需要类似:

constructor(props) {
  super(props);
  this.state = {
    programs: []
  }
}

The this.setState function you can use anywhere else. this.setState您可以在其他任何地方使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM