如何在对象数组中排序键并仅渲染一个对象

时间:2019-04-12 14:37:46

标签: javascript arrays reactjs sorting

我有一系列的行星对象,并且我正在尝试创建一个函数,该函数可以是其中一个行星,并且仅渲染一个行星。

我试图创建一个用于从数组中筛选出行星的函数,但是我没有成功。

sortPlanet() {
const planet  = this.state.sort((a, b) => a.index > b.index )
}

然后我试图在地图前输入一个类型

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;

我的目标是仅对一个星球进行分类,每当我单击“下一步”按钮时,都会调用该函数随机搜索另一个星球。

编辑: 添加示例数据

[
        {
            "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/"
        }
]

2 个答案:

答案 0 :(得分:3)

也许我误会了你想做什么。似乎您不需要对它们进行排序。

如果您想随机使用行星

Math.floor(Math.random() * this.state.data.length)

您可以在状态中使用2个数组,而不仅仅是一个。一种是从中获取随机行星的阵列,另一种是您在其中设置顺序的行星。

如果要渲染一个星球,则不应该绘制所有星球。我会将您的状态更改为

 state = {
    data: [],
    chosenPlanet: 0
  }

并使用

渲染地球
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>)

答案 1 :(得分:0)

因此,到目前为止,您只需花5分钟即可快速获取您提供的代码。我自由地根据您的文本重构某些内容,以使您更符合目标。如果您希望一次仅渲染1个行星,则无需担心渲染整个列表并将其隐藏。使用反应state管理来渲染第1颗行星,当状态改变时,组件将重新渲染并为您提供新的行星。 现在这个:

sortPlanet() {
  const planet  = this.state.sort((a, b) => a.index > b.index )
}

此代码无效。默认情况下,Planet作为对象没有索引。我相信您正在尝试访问数组内部的索引。数组的排序顺序应该无关紧要。您只需要从阵列中随机挑选一颗行星即可。

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;