我可以在函数的回调函数中返回Components吗?

时间:2019-02-05 14:29:32

标签: javascript reactjs callback mern

我希望在数组的映射迭代内安装组件类。因为数组经历了两次转换,所以我有两个函数来处理这个转换,但是最终的组件没有安装。

文章每天以博客形式呈现。借助GraphQL,我可以获得{listDates()}发表文章的所有日期的列表。然后,我只需要获取唯一的日期,并确保它们按相反的顺序{sortDates()}。有了这个数组,我需要将各个日期粘贴到它们自己的组件中,在该组件中将进行另一个查询以呈现当天的所有文章。

import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
import { gql } from "apollo-boost";
import { graphql } from "react-apollo";
import PostsDay from "./postsDay";
var dateFormat = require("dateformat");
var array = require("lodash/array");
var collection = require("lodash/collection");

 const getDatesQuery = gql`
   {
     posts(where: { status: "published" }) {
        published
     }
    }
  `;

 class PostsFeed extends Component {
   sortDates = allDates => {
     let uniqueSortedDates = array.reverse(
       array.uniq(collection.sortBy(allDates))
     );

      uniqueSortedDates.map((d, index) => {
        console.log("should be posting", d);
        return <PostsDay key={index} artDate={d} />;
      });
    };
    listDates = (data, allDates, sortDates) => {
      data.posts.forEach(post => {
        allDates.push(dateFormat(post.published, "yyyy-mm-dd"));
     });
sortDates(allDates);
    };
   render() {
     let data = this.props.data;
let allDates = [];

if (data.loading) {
  return "Loading...";
} else {
  return <div>{this.listDates(data, allDates, this.sortDates)} . 
 </div>;
     }
    }
  }

  export default graphql(getDatesQuery)(
    withStyles(styles, { withTheme: true })(PostsFeed)
   );

我希望所有组件都被加载。控制台读取以下内容:

 should be posting 2017-11-14
 should be posting 2017-11-13
 should be posting 2017-11-11
 should be posting 2017-11-04
 ...

所以我们要进入{sortDates()}函数,但不渲染组件。我不明白。请帮忙。谢谢大家。

1 个答案:

答案 0 :(得分:0)

@Quentin的见解很有帮助。我能够清理代码并使一切正常运行。

class PostsFeed extends Component {
  state = {
    uniqueSortedDates: []
  };

  componentDidUpdate(prevProps) {
    const { data } = this.props;
    if (!data.loading && data.posts !== prevProps.data.posts) {
      this.listDays(data);
    }
  }

  listDays = data => {
    let allDates = [];
    data.posts.forEach(post => {
      allDates.push(dateFormat(post.published, "yyyy-mm-dd"));
    });
    const uniqueSortedDates = array.reverse(
      array.uniq(collection.sortBy(allDates))
    );
    this.setState({ uniqueSortedDates: uniqueSortedDates });
  };

  render() {
    const { uniqueSortedDates } = this.state;
    return (
      <div>
        {uniqueSortedDates.slice(0, 5).map(date => {
          return <PostsDay key={date} artDate={date} />;
        })}
      </div>
    );
  }
}