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

问题描述 投票:0回答:1

我希望在数组的map迭代中挂载一个组件类。因为数组经历了两次转换,所以我有两个函数来处理这个转换,但最后的组件没有被挂载。

文章按日博客风格呈现。使用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()}函数但没有渲染组件。什么我不理解。请帮忙。谢谢你们。

javascript reactjs callback mern
1个回答
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>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.