Line 5: 'props' is not defined no-undef

馋奶兔 提交于 2021-02-10 06:24:08

问题


I'm trying to create a randomiser for the data I get from the API; however I get this "Line 5: 'props' is not defined no-undef" error and don't see what's wrong with it.

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;

回答1:


Like others have said, you have not passed props to the constructor function. Your constructor should look like this:

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

Ultimately, you do not even need a constructor anymore.

Also, I believe your componentDidMount needs a small update. You are not returning your json data here then(response => response.json()) so the next then statement will not be saving anything to state. Simply update that like so:

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

Without the constructor, your update component should look like this:

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>
    )
  }
}

That's it. Should be good to go.




回答2:


You are missing constructor(props) {. props first needs to be received by the constructor function as an argument, then only you can use it. You are missing that part. Otherwise, you will get Uncaught ReferenceError: props is not defined error at runtime.




回答3:


You have to pass props in your constructor like-

constructor(props)


来源:https://stackoverflow.com/questions/53803189/line-5-props-is-not-defined-no-undef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!