第8行:解析错误:这是保留字

时间:2018-12-13 21:35:22

标签: javascript reactjs

我正在尝试制作有关API中每个项目的详细页面;但是它似乎不起作用,它给我一个“第8行:解析错误:这是一个保留字”错误。另外,我不确定我的代码在DetailPage.js中是否正常运行,我想获取详细信息页面主页上单击的项目的数据,因此我检查ID是否与API中的任何ID匹配

我的App.js

import React, { Component } from 'react';
import { BrowserRouter,Route,Switch } from 'react-router-dom';
import Brewery from './components/Brewery'
import DetailPage from './components/DetailPage'
import Menu from './components/Menu'

class App extends Component {
  render() {
    return (
      <div>
      <div> <Menu /> </div>
      <div>
        <BrowserRouter>
          <Switch>
            <Route path="/brewery" component={Brewery} exact/>
            <Route path="/brewery/:id" component={DetailPage} exact/>
          </Switch>
        </BrowserRouter>
      </div>
      </div>
    )
  }
}

export default App;

我的Brewery.js

import React from "react";
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,
        })
      })
  }

  render() {

    const { breweries } = this.state;

    return(
        <ul>
          {breweries.slice(0,10).map((brewery) =>
              <li key={brewery.id}>
                <Link to={`/brewery/${ brewery.id }`}>
                  {brewery.name}
                </Link>
              </li>
          )}
        </ul>
    )
  }
}

export default Brewery;

我的DetailPage.js

import React from "react";
import Brewery from './Brewery'

class DetailPage extends React.Component {
  render() {
    const paramsId = `${this.props.match.params.id}`
    return(
        {this.state.breweries.map((brewery) => {
          if (brewery.id === paramsId) {
            return <div>{brewery.name}</div>
        }})
    )
  }
}
}

export default DetailPage;

1 个答案:

答案 0 :(得分:2)

正如@SLaks在评论中指出的那样,当您从JSX中使用Javascript表达式时,您不需要curl({})。只需直接编写您的表达式即可。

render() {
  // You don't need to use curlies here.
  console.log("foo");
  return (
    // or here if you start your return statement with a Javascript expression.
    foo.map(el => <div>{Here you need it if it is a JS expression}</div>)
  );
}

因此,将顶部的小卷发放在DetailPage组件的返回部分中。但是之后,您将遇到另一个与当前问题无关的问题。在您的DetailPage中,您没有任何breweries状态。您正在Brewery组件中获取它们。因此,DetailPage组件中没有它们。您有一个来自路由器的ID,因此,作为一种幼稚的方法,您可以再次使用它来获取单个啤酒厂。

所以:

class DetailPage extends React.Component {
  state = {
    brewery: {}
  };

  componentDidMount() {
    const { id } = this.props.match.params;
    fetch(`https://api.openbrewerydb.org/breweries/${id}`)
      .then(response => response.json())
      .then(data => {
        this.setState({
          brewery: data
        });
      });
  }
  render() {
    return <p>{this.state.brewery.name}</p>;
  }
}