gpt4 book ai didi

javascript - 如何从数组中渲染随机对象

转载 作者:行者123 更新时间:2023-11-30 19:38:41 28 4
gpt4 key购买 nike

我正在处理数组中的随机对象,但是我无法渲染它

我尝试使用 {planet.name} 进行渲染,并返回(名称未定义):

return (
<div className="App">
<div>{planet.name}</div>
<button onClick={this.renderPlanet}>Next</button>
</div>
)

我尝试使用 {planet} 重新渲染,并返回 (对象作为 React 子对象无效(已找到:带键的对象)):

return (
<div className="App">
<div>{planet}</div>
<button onClick={this.renderPlanet}>Next</button>
</div>
)

应用.JS

import React, { Component } from 'react';
import './App.css';

class App extends Component {
state = {
data: [],
chosenPlanet: 0,
}
componentDidMount() {
const url = 'https://swapi.co/api/planets/'

fetch(url)
.then(response => response.json())
.then(response => {
this.setState({
data: response.results,
})
})
}
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;

我需要返回:

<div className="app-container">
<div>
<h1>{planet.name}</h1>
</div>
<div className="about-container">
<span>Population: {planet.population}</span>
<span>Climate: {planet.climate}</span>
<span>Terrain: {planet.terrain}</span>
<br />
<span>Quantidade de Filmes {planet.films.length}</span>
</div>
</div>

最佳答案

您正在 componentDidMount 中进行 API 调用,因此状态中的数据最初将是一个空数组,并且您正在访问第 0 索引

const index = Math.floor(Math.random() * this.state.data.length)
const planet = this.state.data[index]

你最终得到一个错误planet is undefined,

所以你可以在使用行星值之前添加一个检查

{planet && <div>{planet.name}</div>}

您可以在下面的代码片段中看到一个工作示例

class App extends React.Component {
state = {
data: [],
chosenPlanet: 0,
}
componentDidMount() {
const url = 'https://swapi.co/api/planets/'

fetch(url)
.then(response => response.json())
.then(response => {
this.setState({
data: response.results,
})
})
}
render() {
const index = Math.floor(Math.random() * this.state.data.length)
const planet = this.state.data[index]
return (
<div className="App">
{planet && <div>Name of planet: {planet.name}</div>}
</div>
)
}
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/3.0.0/fetch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id='root'></div>

关于javascript - 如何从数组中渲染随机对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55661259/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com