我正在尝试通过道具将对象传递给用户,以在详细信息页面上向用户显示有关该项目的更多详细信息,但似乎有些东西坏了。它给了我一个'./src/components/Trial.js第38行:分析错误:意外的令牌,预期为“,”'错误
我的brewery.js
import React from "react";
import Trial from './'
import { Link } from 'react-router-dom';
class Brewery extends React.Component {
constructor(props) {
super(props);
this.state = {
breweries: []
};
}
componentDidMount() {
fetch("https://api.openbrewerydb.org/breweries")
.then(response => response.json())
.then((data) => {
this.setState({
breweries: data,
})
})
}
renderBreweries = () => {
const { breweries } = this.state;
return breweries.slice(0,10).map((brewery) =>
<Brewery key={brewery.id} brewery={brewery} />
)
}
render() {
const { breweries } = this.state;
return(
<div>
{this.renderBreweries()}
</div>
)
}
}
export default Brewery;
我的trial.js
import React from "react";
import Brewery from "./Brewery";
class Trial extends React.Component {
render() {
const { brewery } = this.props;
return(
<div>
{brewery.name}
</div>
}
}
export default Trial;
答案 0 :(得分:1)
您正在遇到无限调用,在did mount中创建brew
return breweries.slice(0,10).map((brewery) =>
<Brewery key={brewery.id} brewery={brewery} />
)
每次调用时,您都会再次调用api并获取相同的数据。因此,您永远不会得到结果。
创建一个新组件以呈现结果,或者您可以使用现有组件,但不要递归调用。像这样
export const RenderBreweries=(props) =>{
return <div>{props.brewery.id}</div>
}
并这样称呼
return breweries.slice(0, 10).map((brewery) =>
<RenderBreweries key={brewery.id} brewery={brewery} />
)
这将渲染啤酒酿造厂。是的,您将获得props.key
和props.brewery
您的组件应如下所示
import React from "react";
import Trial from './'
import { Link } from 'react-router-dom';
class Brewery extends React.Component {
constructor(props) {
super(props);
this.state = {
breweries: []
};
}
componentDidMount() {
fetch("https://api.openbrewerydb.org/breweries")
.then(response => response.json())
.then((data) => {
this.setState({
breweries: data,
})
})
}
renderBreweries = () => {
const { breweries } = this.state
return breweries.slice(0, 10).map((brewery) =>
<RenderBreweries key={brewery.id} brewery={brewery} />
)
}
render() {
console.log(this.breweries)
const { breweries } = this.state;
return (
<div>
{this.renderBreweries()}
</div>
)
}
}
export const RenderBreweries=(props) =>{
return <div>{props.brewery.id}</div>
}
export default Brewery;
答案 1 :(得分:0)
在返回Trial.js
后打开括号,再也不要关闭括号。
class Trial extends React.Component {
render() {
const { brewery } = this.props;
return(
<div>
{brewery.name}
</div>
); //<-- missing part
}
}
我建议使用诸如eslint
之类的短绒棉绒,这样可以避免许多错误。
答案 2 :(得分:-1)
您在,
之后有一个额外的breweries: data
(虽然不是这种情况),您是否尝试将其删除?
componentDidMount() {
fetch("https://api.openbrewerydb.org/breweries")
.then(response => response.json())
.then((data) => {
this.setState({
breweries: data,
})
})
}
以及下面的内容中也缺少括号,您可以如下更改Trial
class Trial extends React.Component {
render() {
return(
<div>
{this.props.brewery.name}
</div>
); // here
}
}
因此,当您要进行试用时,应该使用
<Trial brewery={brewery} />