首页 > 解决方案 > 如何创建一个选择另一个对象并在浏览器中刷新的函数

问题描述

我正在尝试创建一个函数,当单击“下一步”按钮时传递给我的 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;

标签: javascriptreactjs

解决方案


在事件处理程序中,必须更新状态。状态更新导致组件更新自身或重新渲染。在这种情况下,由于没有改变状态,只需要触发更新,因此可以使用 forceUpdate。

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

推荐阅读