【问题标题】:how can i store a sorted object using redux如何使用 redux 存储已排序的对象
【发布时间】: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


【解决方案1】:

更新:不一定要使用 redux 对元素进行排序。 Redux 用于状态管理。您可以参考下面提到的教程链接。它包含对redux的深入解释: https://chriscourses.com/blog/redux

注意:正如评论中所建议的,最佳做法是从后端本身获取排序响应。

尽管如果您仍想在前端对响应进行排序。假设您得到以下类型的响应:

const allPosts = [
  {
    title: 'Charming Post',
    author: 'Brian',
    description: 'Lorem ipsum etc etc'
  },
  {
    title: 'Amazing Post',
    author: 'Chadwick',
    description: 'Lorem ipsum etc etc'
  },
  {
    title: 'Boring Post',
    author: 'Alex',
    description: 'Lorem ipsum etc etc'
  },
];

在将帖子存储在 redux 中之前,即在 HomePage.js 内的 AllPosts 函数(API 调用)中,您可以在存储响应之前对其进行排序(setPosts() 函数调用),如下所示:

// by title
const newPostsByTitle = allPosts.sort((a, b) =>  a.title.localeCompare(b.title));

//by author
const newPostsByAuthor = allPosts.sort((a, b) =>  a.author.localeCompare(b.author));

console.log('sorted by title', newPostsByTitle);
console.log('sorted by author', newPostsByAuthor);

然后您可以按如下方式存储排序后的响应:

setPosts(newPostsByTitle); // for sorted by title

setPosts(newPostsByAuthor); // for sorted by author

【讨论】:

  • 谢谢尼拉吉。我会相应地实施。
  • 我应该从 react-redux 导入什么?
  • 在使用 setPosts() 函数时无需导入任何内容,在该函数中传递已排序的数据。
  • 哦,我明白了,您似乎不知道react-redux。好吧,您可以按照下面的教程进行操作,详细说明如何使用 redux 实现它:chriscourses.com/blog/redux
  • 谢谢。但是我怎样才能将排序的对象渲染到屏幕上。对不起,我对 redux 有基本的了解。
【解决方案2】:
  const AllPosts = () => {
        axios
          .get(`${url}`, { headers: config })
    
          .then((response) => {
            const allPosts = response.data.articles;
            const newPostsByTitle = allPosts.sort((a, b) =>
              a.title.localeCompare(b.title)
            );
            const newPostsByAuthor = allPosts.sort((a, b) =>
              a.author.localeCompare(b.author)
            );
            const newPostsByurlToImage = allPosts.sort((a, b) =>
              a.urlToImage.localeCompare(b.urlToImage)
            );
            const newPostsByDescription = allPosts.sort((a, b) =>
              a.description.localeCompare(b.description)
            );
    
            console.log("sorted by title", newPostsByTitle);
            console.log("sorted by author", newPostsByAuthor);
            console.log("sorted by image", newPostsByurlToImage);
            console.log("sorted by description", newPostsByDescription);
            console.log(response);
            setPosts(allPosts);
            setPosts(newPostsByTitle);
            setPosts(newPostsByAuthor);
            setPosts(newPostsByurlToImage);
            setPosts(newPostsByDescription);
          })
          .catch((error) => console.error(`Error: ${error}`));
      };

  return (
    <div>
      <Post className="Posts" posts={posts} key={posts.title} />
    </div>
  );

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多