单击按钮时提供新项目

时间:2018-12-17 09:36:52

标签: javascript reactjs

我正在尝试使此页面上的按钮打印另一个随机项目。我创建了函数,然后单击按钮,控制台中出现了一个新对象。但是它不会打印在页面上。

import React from "react";
import './Random.css'

class Random 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,
        })
      })
  }

  reloadPage() {
    const brewery = this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
    console.log(brewery)
  }

  render() {
    const brewery = this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
    console.log(brewery)
    return(
    <div className="main">
      <div className="details">
          <p><b>Name:</b> {brewery && brewery.name}</p>
          <p className="category"><b>Category:</b> {brewery && brewery.brewery_type}</p>
          <p><b>Address:</b> {brewery && brewery && brewery.street}, {brewery && brewery.city},
      {brewery && brewery.state}, {brewery && brewery.postal_code}, {brewery && brewery.country}</p>
          <p><b>Phone Number:</b> {brewery && brewery.phone}</p>
          <p><b>Website:</b> <a href={brewery && brewery.website_url} target="_blank">{brewery && brewery.website_url}</a></p>
      </div>
      <div className="button">
        <button onClick={() => this.reloadPage()}>Get another random item</button>
      </div>
    </div>
    )
  }
}

export default Random;

1 个答案:

答案 0 :(得分:2)

您需要this.setState()

reloadPage() {
    const brewery = this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
    console.log(brewery)
this.setState({breweries:brewery})
  }

但是在渲染中,您将再次将其随机化

更好

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

  reloadPage() {
    const brewery = this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
 this.setState({breweries:brewery})
  }

  render() {
    const brewery = this.state.breweries.length > 1 && this.state.breweries[0];