[英]How to sort a key in array of object and render just one object
I have an array of planet objects and I'm trying to create a function that sort of one of those planets and render only a planet. 我有一系列的行星对象,并且我试图创建一个函数,使这些行星之一仅渲染一个行星。
I tried to create a function for sort out a planet from the array, but I did not succeed. 我试图创建一个用于从阵列中选出行星的函数,但没有成功。
sortPlanet() {
const planet = this.state.sort((a, b) => a.index > b.index )
}
and I tried to make a type before the map 我试图在地图前打一个字
const { data } = this.state
const planets = data
.sort((a, b) => a.index > b.index )
.map((planet, index) => {
return (<div key={index} 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>{planet.films.length}</span>
</div>
</div>)
})
import './App.css';
class App extends Component {
state = {
data: [],
}
componentDidMount() {
const url = 'https://swapi.co/api/planets/'
fetch(url)
.then(response => response.json())
.then(response => {
this.setState({
data: response.results,
})
})
}
render() {
const { data } = this.state
const planets = data
.map((planet, index) => {
return (<div key={index} 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>{planet.films.length}</span>
</div>
</div>)
})
console.log(planets)
return (
<div className="App">
{planets}
<button>Next</button>
</div>
)
}
}
export default App;
my goal is to sorter just one planet to display and whenever I click the "next" button call the function to randomly search another planet. 我的目标是仅对一个星球进行分类,每当我单击“下一步”按钮时,都会调用该函数随机搜索另一个星球。
EDIT: add example data 编辑:添加示例数据
[
{
"name": "Alderaan",
"rotation_period": "24",
"orbital_period": "364",
"diameter": "12500",
"climate": "temperate",
"gravity": "1 standard",
"terrain": "grasslands, mountains",
"surface_water": "40",
"population": "2000000000",
"residents": [
"https://swapi.co/api/people/5/",
"https://swapi.co/api/people/68/",
"https://swapi.co/api/people/81/"
],
"films": [
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/1/"
],
"created": "2014-12-10T11:35:48.479000Z",
"edited": "2014-12-20T20:58:18.420000Z",
"url": "https://swapi.co/api/planets/2/"
},
{
"name": "Yavin IV",
"rotation_period": "24",
"orbital_period": "4818",
"diameter": "10200",
"climate": "temperate, tropical",
"gravity": "1 standard",
"terrain": "jungle, rainforests",
"surface_water": "8",
"population": "1000",
"residents": [],
"films": [
"https://swapi.co/api/films/1/"
],
"created": "2014-12-10T11:37:19.144000Z",
"edited": "2014-12-20T20:58:18.421000Z",
"url": "https://swapi.co/api/planets/3/"
},
{
"name": "Hoth",
"rotation_period": "23",
"orbital_period": "549",
"diameter": "7200",
"climate": "frozen",
"gravity": "1.1 standard",
"terrain": "tundra, ice caves, mountain ranges",
"surface_water": "100",
"population": "unknown",
"residents": [],
"films": [
"https://swapi.co/api/films/2/"
],
"created": "2014-12-10T11:39:13.934000Z",
"edited": "2014-12-20T20:58:18.423000Z",
"url": "https://swapi.co/api/planets/4/"
}
]
Maybe I'm misunderstanding what you are trying to do. 也许我误会了您要做什么。 Seems like you don't need to sort them.
似乎您不需要对它们进行排序。
if you want a random planet use 如果您想随机使用行星
Math.floor(Math.random() * this.state.data.length)
You could use 2 arrays in your state instead of just one. 您可以在状态中使用2个数组,而不仅仅是一个。 One array where you are getting a random planet from and one that you are setting the order of.
一种是从中获取随机行星的数组,另一种是您要设置其顺序的数组。
if you want to render one planet you shouldn't be mapping all of them. 如果要渲染一个星球,则不应该绘制所有星球。 i would change your state to
我会将您的状态更改为
state = {
data: [],
chosenPlanet: 0
}
and render the planet useing 并使用
const index = this.state.chosenPlanet;
const planet= this.state.data[index]
const renderPlanet =
(<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>{planet.films.length}</span>
</div>
</div>)
So here was a quick 5-minute take on your code provided so far. 因此,这里是您到目前为止提供的代码的5分钟快速介绍。 I took the liberty of refactoring some things based on your text to align you more with your goal.
我自由地根据您的文本重构某些内容,以使您更符合目标。 If you are looking to just render 1 planet at a time, you don't need to worry about rendering an entire list and hiding it.
如果您希望一次仅渲染1个行星,则无需担心渲染整个列表并将其隐藏。 Use reacts
state
management to render the 1 planet, when that state changes, the component will re-render and give you your new planet. 使用反应
state
管理来渲染第1颗行星,当该状态改变时,组件将重新渲染并为您提供新的行星。 Now this: 现在这个:
sortPlanet() {
const planet = this.state.sort((a, b) => a.index > b.index )
}
This code wont work. 此代码无法正常工作。 Planet as an object does NOT have an index by default.
默认情况下,Planet作为对象没有索引。 I believe you are trying to access the indices inside of the array.
我相信您正在尝试访问数组内部的索引。 The sort order of the array should be irrelevant.
数组的排序顺序应该无关紧要。 All you care about is randomly picking a planet from the array.
您只需要从阵列中随机挑选一颗行星即可。
class App extends Component {
constructor(props) {
super(props);
const url = 'https://swapi.co/api/planets/';
state = {
randomPlanet: 0,
planets: fetch(url) // make your fetch here, it is cleaner and better
.then((response) => response.json())
.then((response) => {
return response.sort((a, b) => a.name - b.name);
}),
};
}
// you dont want to render the entire list, you just want to render one at a time randomly
renderPlanet() {
const { planets, randomPlanet } = this.state;
const planet = planets[randomPlanet];
return (
<div key={index} 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>{planet.films.length}</span>
</div>
</div>
);
}
// get a random number between 0 and the numbe of planets, use that to access the index of your planets array
getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
// update the current randon planet in state to get your next random planet
getNextPlanet = () => {
this.setState(({planets}) => ({
randomPlanet: getRandomArbitrary(0, planets.length),
}));
};
render() {
return (
<div className='App'>
{this.renderPlanet()}
<button onPress={this.getNextPlanet}>Next</button>
</div>
);
}
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.