用react钩子对数组排序

时间:2019-09-24 20:43:01

标签: javascript reactjs react-hooks

我正在做一个简单的带有react钩子的数组,但是它没有更新状态。谁能指出我要去这里吗?

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const dogs = [{ name: "fido", age: 22 }, { name: "will", age: 50 }];

function App() {
  const [dogList, setDogList] = useState(dogs);

  const sortByAge = () => {
    const sorted = dogList.sort((a, b) => {
      return b.age - a.age;
    });
    setDogList(sorted);
    alert(sorted[0].name);
  };

  return (
    <div>
      {dogs.map((dog, i) => {
        return <p key={i}>{dog.name}</p>;
      })}
      <div onClick={sortByAge}>sort by age</div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

2 个答案:

答案 0 :(得分:3)

首先:由于Array.prototype.sort()就位,因此在进行排序之前先进行克隆:

const sorted = [...dogList].sort((a, b) => {
  return b.age - a.age;
});

否则,更改检测将不会检测到更改的阵列。

您在dogs上调用地图。修复:

  return (
    <div>
      {dogList.map((dog, i) => {
        return <p key={i}>{dog.name}</p>;
      })}
      <div onClick={sortByAge}>sort by age</div>
    </div>
  );

演示:https://jsfiddle.net/acdcjunior/kpwb8sq2/1/

答案 1 :(得分:1)

const dogs = [{ name: "fido", age: 22 }, { name: "will", age: 50 }];
class Application extends React.Component {
  state = {dogList: dogs};

  sortByAge = () => {
    const sorted = this.state.dogList.sort((a, b) => {
      return b.age - a.age;
    });
    this.setState({dogList: sorted});
  };

  render() {
    return (
      <div>
        {this.state.dogList.map((dog, i) => {
          return <p key={i}>{dog.name}</p>;
        })}
        <button onClick={this.sortByAge}>sort by age</button>
      </div>
    );
  }
}
React.render(<Application />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.min.js"></script>
<div id="root"></div>

这是使用钩子的代码

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

const dogs = [{ name: "fido", age: 22 }, { name: "will", age: 50 }];
function Application() {
  const [dogList, setDogList] = useState(dogs);
  const sortByAge = () => {
    const sorted = dogList.sort((a, b) => {
      return b.age - a.age;
    });
    setDogList(sorted);
  };
  return (
    <div>
      {dogList.map((dog, i) => {
        return <p key={i}>{dog.name}</p>;
      })}
      <button onClick={sortByAge}>sort by age</button>
    </div>
  );
}

ReactDOM.render(<Application />, document.getElementById('root'));