【发布时间】:2021-05-01 04:13:07
【问题描述】:
如何添加 redux 进行排序。我正在尝试使用 redux 对返回 JSON 数组的 api 进行排序。有人可以帮助我,因为我是 Redux 的新手。在 HomePage.js 下面我添加了 post.js
Redux 是进行排序的要求。由于我是 redux 的新手,我不确定如何处理
主页.js
import React, { useState, useEffect } from "react";
import Post from "../../Components/Post/Post";
import axios from "axios";
const HomePage = () => {
const [posts, setPosts] = useState("");
let config = { Authorization: "**********" };
const url = "https://*************";
useEffect(() => {
AllPosts();
}, []);
const AllPosts = () => {
axios
.get(`${url}`, { headers: config })
.then((response) => {
const allPosts = response.data.articles;
console.log(response);
setPosts(allPosts);
})
.catch((error) => console.error(`Error: ${error}`));
};
return (
<div>
<Post className="Posts" posts={posts} />
</div>
);
};
export default HomePage;
Post.js
import React from "react";
import "./Post.css";
import { Fragment } from "react";
const Post = (props) => {
const displayPosts = (props) => {
const { posts } = props;
if (posts.length > 0) {
return posts.map((post) => {
return (
<Fragment>
<div className="Post" key={post.title}>
<img
src={post.urlToImage}
alt="covid"
width="100%"
className="img"
/>
<h5 className="title"> {post.title}</h5>
<p className="author"> {post.author}</p>
<p className="description"> {post.description}</p>
</div>
</Fragment>
);
});
}
};
return <div className="Posts">{displayPosts(props)}</div>;
};
export default Post;
【问题讨论】:
-
只想添加评论。由于您已发布到公共场所,请隐藏您的授权数据并轮换密钥。
-
另外,我们需要更多信息,比如 Post 是什么样的,如果您只需要排序,我们真的需要 Redux 吗?
-
@NanoBit 是的,我必须使用 Redux 来完成。我现在也在更新 post.js
-
我认为你不需要 Redux。只需在此行拨打
const allPosts = response.data.articles.sort();并选择您想要排序的内容。这是 JS 中另一种排序的链接,因为我不知道您要按什么排序。 stackoverflow.com/questions/979256/… -
@alex,Post 是否来自您的后端?如果是这样,那么最好从后端发送已排序的响应。
标签: reactjs redux react-redux react-hooks