javascript - 我可以在函数的回调函数中返回组件吗?
问题描述
我希望在数组的映射迭代中安装一个组件类。因为数组经历了两次转换,所以我有两个函数来处理这个转换,但最终的组件没有被安装。
文章每天以博客风格呈现。使用 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()} 函数但不渲染组件。我不明白什么。请帮忙。谢谢你们。
解决方案
@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>
);
}
}
推荐阅读
- python - Python 列出原始 Cloudwatch 指标值
- python - 由于 tclError,使用 tkinter 的 python 程序无法运行
- c++ - 使用 Eigen3 的 CGAL 程序编译错误
- python - Pandas DataFrame 枢轴(重塑?)
- python - 在 Python 中使用 any()
- javascript - 如何解决护照认证产生的错误
- javascript - 将 CSS Lch 转换为 RGB
- typescript - 使用泛型时,打字稿有条件产生没有结果
- vue.js - VueJS:动态组件在重新加载后丢失了它的道具
- python - 如何尝试〜除了在Python中?