将字典列表设置为 React 中的状态

Set the list of dict to the state in React

我有一个 od 字典列表。它看起来像这样:

document.__moreComments = [
  { id: 2, author: '...', text: '...', date: '...' },
  { id: 1, author: '...', text: '...', date: '...' },
];

我想按日期对我的数据进行排序并呈现它。 首先,我想在声明中创建一个对象并将其设置为状态。然后排序并表示变化的数据。我有个问题。

import React, { Component } from "react";

var addcomments = document.__moreComments;

class AdditionalComments extends Component {
  constructor() {
    super();
    //    this.state = addcomments

    this.state = {
      comments: addcomments.map(addcomment => [
        addcomment.id,
        addcomment.author,
        addcomment.text,
        addcomment.date
      ])
    };
    console.log(this.state);
  }

  changeMessage() {
    let sortedComments = this.state.comments;
    this.setState({
      comments: sortedComments.sort((a, b) => a.date > b.date)
    });
    console.log(this.state.comments);
  }
  render() {
    return (
      <div>
        <h1>hi Eugene {this.state.comments} </h1>
        <button onClick={() => this.changeMessage()}>Click</button>
      </div>
    );
  }
}

export default AdditionalComments;

我创建了 dict of dict。我当然想知道。做我做的事是正确的还是我需要另一种方法? 谢谢。我是初学者。

Sort 就地对数组进行排序(这意味着它不会 return 数组的新实例),这就是您的数组未排序的原因。您应该尝试以下方法:

changeMessage() {
    let sortedComments = [...this.state.comments].sort((a,b) => new Date(a.date) - new Date(b.date))
    this.setState({
      comments: sortedComments
    }, () => {console.log(this.state.comments)});
  }