问题
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