javascript - 如何创建一个选择另一个对象并在浏览器中刷新的函数
问题描述
我正在尝试创建一个函数,当单击“下一步”按钮时传递给我的 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();
}
推荐阅读
- ios - 无论我在应用程序中的哪个位置,当我单击通知时如何转到收件箱选项卡?
- python - 我需要使用 python 请求库对 URL 执行 GET 请求并仅获取最后 100 行
- c# - RabbitMQ 使用 REST API 发布消息
- asp.net-web-api - 单击按钮时调用控制器操作
- makefile - 自动依赖检测在 GFortran 中不起作用
- python - tkinter 使用 python 3.7 的基本查询
- python - 需要使用python提取html元素中的信息并打印它
- apache - 查找查询标记“?”之前的数据 在网址中
- django - /basic_app/register/ 处的 AttributeError:'tuple' 对象没有属性 'get'
- css - CCS Flexbox 挑战 - 内容未按要求排列在框中