我正在处理数组中的随机对象,但是无法渲染
我尝试使用{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>
)
App.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>
答案 0 :(得分:1)
您正在componentDidMount
中进行API调用,因此您处于状态的数据最初将是一个空数组,并且您正在访问0 th 索引
const index = Math.floor(Math.random() * this.state.data.length)
const planet = this.state.data[index]
您最终会遇到错误planet is undefined
,
因此您可以在使用planet值之前添加支票
{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>