如何创建选择另一个对象并在浏览器中刷新的函数



我正在尝试创建一个函数,当单击"下一步"按钮时,该函数会传递给我的 API 的另一个随机对象。但是我无法执行检索其他值并在浏览器中更新信息的函数。

应用.js

import React, { Component } from 'react';
import './App.css';
class App extends Component {
  state = {
    data: [],
    chosenPlanet: 0,
  }
  componentDidMount() {
    const url = 'http://localhost:4000/results'
    fetch(url)
      .then(response => response.json())
      .then(response => {
        this.setState({
          data: response.results,
        })
      })
  }
renderPlanet = (event) => {
const planetRandom = Math.floor(Math.random() * this.state.data)
return planetRandom
}
  render() { 
    const index = Math.floor(Math.random() * this.state.data.length)
    const planet = this.state.data[index]
    console.log(planet)
    return (
      <div className="App">
         <div>{this.planet.name}</div>
        <button onClick={this.renderPlanet}>Next</button>
      </div>
    )
  }
}
export default App;

在事件处理程序中,必须更新状态。状态更新会导致组件自行更新或重新呈现。在这种情况下,由于没有更改任何状态,并且只需要触发更新,因此可以使用 forceUpdate。

handleNext = (event) => {
  this.forceUpdate();
}

最新更新