首页 > 解决方案 > 如何使用 UseMemo ReactHooks 呈现已排序的对象数组

问题描述

我正在尝试使用 ReactHooks 渲染排序的对象数组,我也使用了 useMemo 和 redux。有人可以建议我最好的做法。关于我在这里做错了什么有什么建议吗?

我也把 post.js 放在了下面。

我正在尝试使用 ReactHooks 渲染排序的对象数组,我也使用了 useMemo 和 redux。有人可以建议我最好的做法。关于我在这里做错了什么有什么建议吗?

谢谢

主页.js

import React, { useState, useEffect, useMemo } from "react";
    import Post from "../../Components/Post/Post";
    import "./HomePage.css";
    import axios from "axios";
    
    const HomePage = () => {
      const [posts, setPosts] = useState("");
    
      let config = { Authorization: "................" };
      const url = ".........................";
    
      useEffect(() => {
        AllPosts();
      }, []);
    
      const AllPosts = () => {
        axios
          .get(`${url}`, { headers: config })
    
          .then((response) => {
            const allPosts = response.data.articles;
            console.log(response);
          })
          .catch((error) => console.error(`Error: ${error}`));
      };
    
      const newPostsByTitle = useMemo(() => {
        allPosts.sort((a, b) => a.title.localeCompare(b.title)), [posts];
      });
    
      return (
        <div className="home">
          <div className="select">
            <select
              name="slct"
              id="slct"
              onChange={(e) => newPostsByTitle(e.target.value)}
            ></select>
          </div>
          <Post className="Posts" posts={posts} key={posts.title} />
        </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;

标签: reactjsreact-reduxreact-hooks

解决方案


您对我认为的 axios 调用 dos 的理解不正确。这只是一个触发时将下载数据的函数,但您需要将其存储在某处(例如帖子)并使用这些帖子而不是 api 调用:

const [posts, setPosts] = useState([]); // Use an empty array as defualt so it does work without data before the call
...
  const AllPosts = () => {
        axios
          .get(`${url}`, { headers: config })
    
          .then((response) => {
            const allPosts = response.data.articles;
           setPosts(allPosts) ?? You need to save the posts somewhere, since allPosts is not accessible outside of this function. Sicne you already have a useState, save them there
            console.log(response);
          })
          .catch((error) => console.error(`Error: ${error}`));
      };
    
const newPostsByTitle = useMemo(() => {
    return posts.sort((a, b) => a.title.localeCompare(b.title)), [posts]; // Using {} requeores the return keyword, if you omit the {} you dont need the return statement
}); // Now access the posts saved in state to sort them

<Post className="Posts" posts={posts} key={posts.title} />不起作用,因为帖子是一个数组而不是一个对象。所以删除它。


推荐阅读