繁体   English   中英

第5行:“道具”未定义为no-undef

[英]Line 5: 'props' is not defined no-undef

我正在尝试为从API获得的数据创建随机数; 但我得到这个“第5行:'道具'没有定义no-undef”错误,并且看不出它有什么问题。

import React from "react";

class Random extends React.Component {
  constructor() {
    super(props);
    this.state = {
      breweries: []
    };
  }

  componentDidMount() {
    fetch("https://api.openbrewerydb.org/breweries")
      .then(response => response.json())
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

  render() {
    const brewery = this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
    return(
      <div>{brewery.id}</div>
    )
  }
}

export default Random;

你缺少constructor(props) { props首先需要被constructor函数作为参数接收,然后才能使用它。 你错过了这一部分。 否则,您将获得Uncaught ReferenceError: props is not defined在运行时Uncaught ReferenceError: props is not defined错误。

就像其他人说过的那样,你没有将props传递给构造函数。 您的构造函数应如下所示:

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

最终,你甚至不再需要构造函数了。

另外,我相信你的componentDidMount需要一个小的更新。 不必返回您json这里的数据then(response => response.json())所以接下来then声明将不保存任何东西state 只需像这样更新:

componentDidMount() {
    fetch("https://api.openbrewerydb.org/breweries")
      .then(response => {
         return response.json();
       })
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

如果没有构造函数,您的更新组件应如下所示:

import React, { Component } from "react";

export default class Random extends Component {
  state = { breweries: [] }; 

  componentDidMount() {
    fetch("https://api.openbrewerydb.org/breweries")
      .then(response => {
      return response.json();
      })
      .then((data) => {
        this.setState({
          breweries: data,
        })
      })
  }

  render() {
    const brewery = this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
    return(
      <div>{brewery.id}</div>
    )
  }
}

而已。 应该好好去。

你必须在你的构造函数中传递道具,如 -

constructor(props)

暂无
暂无

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

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