【问题标题】:Can you sort an array of react components? Accessing info of react componenet你能对一系列反应组件进行排序吗?访问反应组件的信息
【发布时间】:2020-05-13 01:54:06
【问题描述】:

我有一个帖子数组,我试图按日期排序 - 但我不知道如何访问日期,因为数组是一个反应组件列表,而不是对象。以下是代码现在的工作方式...

用户搜索“bands”并创建一个包含所有带对象的数组。每个乐队对象在 band.posts 中都有一堆帖子。因此,为了从所有乐队中获取所有帖子,我映射了所有乐队,然后对于每个乐队,我映射了他们所有的帖子。然后每个帖子都会通过函数“convertPost()”将其转换为组件。我现在有一系列帖子组件。这就是我要排序的。这是完成所有这些的代码 -

{bandTypes === 'all' ? allBands.map(band => {
    if(band.youtube.length > 0 && band.bandBio !== 'n/a' && band.bandGenre !== 'n/a'){
        return band.posts.map(post => {
            let currPost = convertPost(post, band)
            return currPost
        })
    }
}).forEach(post => console.log(post)) : null}

我使用 .forEach() 来控制台记录每个帖子 - 它返回反应组件的控制台日志...日期位于 props.post.date

    0:
$$typeof: Symbol(react.element)
key: "NOLA DUDES"
props:
    addFavorites: (userId, band) => {…}
    band: {quoteGenerator: Array(0), youtube: Array(1), posts: Array(2), favorites: Array(1), _id: "5eb20ce78b8cee4494eb44a0", …}
    bandBio: "This is my new band bioThis is my new band bioThis is my new band bioThis is my new band bioThis is my new band bioThis is my new band bio"
    bandName: "NOLA DUDES"
    favorites: ["5e8b54337d9c710ca6f117fa"]
    id: "5eb20ce78b8cee4494eb44a0"
    post:
        approved: null
        data: ""
        date: "2020-05-06T01:03:35.818Z"
        postId: "55445155-0690-46d4-a3bb-4cfd2ea160c3"
        rockOn: []
        type: "band"
__proto__: Object
youtube: ["4_eLn4B9MzQ"]
key: (...)
get key: ƒ ()
__proto__: Object
ref: null
type: ƒ BandCard(props)
_owner: FiberNode {tag: 0, key: null, stateNode: null, elementType: ƒ, type: ƒ, …}
_store: {validated: false}
_self: null
_source: {fileName: "/Users/NickMcLean/Desktop/REACT/AutoQuoteGenerator…t/src/components/Profile/SearchInputs/MainFeed.js", lineNumber: 209, columnNumber: 25}
__proto__: Object
1: {$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}
length: 2
__proto__: Array(0)

所以我尝试了这个......你知道如何访问这个日期,以便我可以按日期对这个帖子数组进行排序吗?我知道这不是获取道具的正常方式...

{bandTypes === 'all' ? allBands.map(band => {
    if(band.youtube.length > 0 && band.bandBio !== 'n/a' && band.bandGenre !== 'n/a'){
        return band.posts.map(post => {
            let currPost = convertPost(post, band)
            return currPost
        })
    }
}).sort((a, b) => b.props.post.date - a.props.post.date) : null}

我还尝试在执行“convertPost()”函数之前对对象进行排序……但转换后函数需要“band”参数才能工作,该参数只能在地图中找到。

{bandTypes === 'all' ? allBands.map(band => {
    if(band.youtube.length > 0 && band.bandBio !== 'n/a' && band.bandGenre !== 'n/a'){
        return band.posts.map(post => {
            return post
        })
    }
}).sort((a, b) => b.date - a.date).forEach(post => {
    let currPost = convertPost(post, band)
    return currPost
}) : null}

这里是 convertPosts 函数

    const convertPost = (post, band) => {
        if(genre === 'Genre'){
            switch (post.type) {
                case "video":
                    return (
                        <VideoPosts key={post.postId} addFavorites={addFavorites} favorites={band.favorites} addRockOn={addRockOn} link={post.data} band={band} post={post} _id={band._id} />
                    )
                case "text":
                    return (
                        <FeedPosts key={post.postId} addFavorites={addFavorites} favorites={band.favorites} addRockOn={addRockOn} band={band} post={post} _id={band._id}/>
                    )   
                case "show":
                    return (
                        <ShowsPosts key={post.postId} addFavorites={addFavorites} favorites={band.favorites} addRockOn={addRockOn} band={band} post={post} _id={band._id}/>
                    )
                case "band":
                    return (
                        <BandCard id={band._id} key={band.bandName} youtube={band.youtube} bandName={band.bandName} bandBio={band.bandBio} post={post} addFavorites={addFavorites} favorites={band.favorites} band={band} />
                    )
                case 'instagram':
                    return (
                        <InstagramPosts key={post.postId} addFavorites={addFavorites} favorites={band.favorites} addRockOn={addRockOn} band={band} post={post} _id={band._id} />
                    )
                default: 
                    return null;
            }
        }else {
            if(band.bandGenre === genre ){
                switch (post.type) {
                    case "video":
                        return (
                            <VideoPosts addFavorites={addFavorites} favorites={band.favorites} addRockOn={addRockOn} link={post.data} band={band} post={post} />
                        )
                    case "text":
                        return (
                            <FeedPosts addFavorites={addFavorites} favorites={band.favorites} addRockOn={addRockOn} band={band} post={post} _id={band._id} />
                        )   
                    case "show":
                        return (
                            <ShowsPosts addFavorites={addFavorites} favorites={band.favorites} addRockOn={addRockOn} band={band} post={post} _id={band._id}/>
                        )
                    case "band":
                        return ( <BandCard id={band._id} key={band.bandName} youtube={band.youtube} bandName={band.bandName} bandBio={band.bandBio} addFavorites={addFavorites} favorites={band.favorites} band={band}/>
                        )
                    default: 
                        return null;
                }
            }
        }

    }

帖子格式 -

        {
            "type": "instagram",
            "data": "https://scontent-dfw5-1.xx.fbcdn.net/v/t51.2885-15/94831976_156494885869068_8673191033070945504_n.jpg?_nc_cat=103&_nc_sid=8ae9d6&_nc_ohc=BOk-_e1RMVwAX-w2ywz&_nc_ht=scontent-dfw5-1.xx&oh=f19acf2fab558ce0d2a79fba3d90db71&oe=5EE1F652",
            "link": "http://www.instagram.com/on_deband_booking",
            "date": "2020-04-28T16:32:40+0000",
            "postId": "18033963559249859",
            "rockOn": []
        },
        {
            "type": "text", //Really this is facebook
            "data": "Have you gotten that special someone, or...someone's, a valentine yet (we mean your favorite local bands)? This Valentine On DeBand is giving you a way to say thank you and show your appreciation to local bands and artists with a special gift (or you can gift it to yourself if you want, no harm in treating yo self)! Tomorrow is the big day, just follow this link: https://www.ondeband.com/happy-valentines/ \n\nDon't forget to follow us for all things music!\n*\n*\n*\n*\n#ondeband #band #music #valentines #specialsomeone #local #localmusic #localband #venue #rockshow #rock #country #metal #pop #punk #emo #love #gratitude #happyheartday",
            "link": "http://www.facebook.com/107460777308513_199513551436568",
            "date": "2020-02-13T16:14:34+0000",
            "postId": "107460777308513_199513551436568",
            "rockOn": []
        },
        {
            "type": "band",
            "data": "",
            "date": "2020-05-05T23:43:53.002Z",
            "postId": "c51295fe-14b0-4a19-9cc3-87da2a28c93f",
            "approved": null,
            "rockOn": []
        },
        {
            "type": "video",
            "data": "PuBqEdb464g",
            "date": "2020-05-05T22:40:23.958Z",
            "postId": "af28c07e-49cb-4b3c-9c6e-452112e1026a",
            "rockOn": []
        },
        {
            "date": "2020-05-05T22:54:59.673Z",
            "type": "show",
            "client": "email",
            "clientId": "5e8b54337d9c710ca6f117fa",
        }

【问题讨论】:

    标签: reactjs sorting react-props


    【解决方案1】:

    您首先要做的是将reduceallBands 数组放入一个包含所有帖子的数组中,不要进行任何嵌套。要同时保留 postband 值,您可以将它们组合成一个对象。然后您可以按日期sort 它,但它在您的数据中表示。

    使用已经创建的组件做任何事情通常是个坏主意,我不鼓励这样做。

    代码如下:

    {
        bandTypes === "all"
            ? allBands
                  .reduce(
                      (allPosts, band) =>
                          allPosts.concat(
                              (band.youtube.length > 0 &&
                                  band.bandBio !== "n/a" &&
                                  band.bandGenre !== "n/a")
                                  ? band.posts.map((post) => ({ post, band }))
                                  : []
                          ),
                      []
                  )
                  .sort((a, b) => new Date(b.post.date) - new Date(a.post.date))
                  .map(({ post, band }) => convertPost(post, band))
            : null;
    }
    
    

    你可以找到更多关于reduce的信息here

    【讨论】:

    • 哇——快到了。看起来它会完美地工作,但是当 convertPost() 发生时,它会按帖子类型对帖子进行排序......然后是日期。例如 - 它按日期对所有 facebook 帖子进行排序,然后按日期对所有 instagram 帖子进行排序,然后按日期对所有本地帖子进行排序。而不是在类型之间混合和匹配。我将在上面发布 convertPosts() 函数
    • @NickMcLean 我猜每个平台都有不同的日期格式。您能否发布一些示例,说明每个帖子来源的日期是什么样的?
    • 我在上面发布了不同的帖子对象。
    • .sort((a, b) => new Date(b.post.date) - new Date(a.post.date)) 似乎在做!
    • 只有一个问题......之前的 if 语句,它的工作,不再像我期望的那样起作用。 - if(band.youtube.length > 0 && band.bandBio !== 'n/a' && band.bandGenre !== 'n/a'){...map the posts} 现在它过滤掉了一些真正具有这些品质的乐队。 -- allPosts 是从哪里来的?
    【解决方案2】:

    为什么不在映射到 post 组件之前先对对象进行排序?

    {
    bandTypes === "all"
      ? allBands
          .map((band) => {
            if (
              band.youtube.length > 0 &&
              band.bandBio !== "n/a" &&
              band.bandGenre !== "n/a"
            ) {
              return band.posts;
            }
          })
          .sort((a, b) => b.date - a.date)
          .map((post) => {
            let currPost = convertPost(post, band);
            return currPost;
          })
      : null;
    }
    

    【讨论】:

    • 嗯。我尝试了一些类似的事情但没有成功。上面的代码说 "TypeError: Date(...).getTime is not a function" 。不管怎样……那不是只对每个乐队的帖子进行排序,而不是对所有乐队的帖子进行排序吗?
    • 我也试过 Date(a.date).getTime() - 返回未定义。
    • 我不知道您的对象的格式,因此转换为日期可能是错误的方法,但想法是一样的。为了清楚起见,我编辑了我的帖子,基本上在映射到组件之前对对象进行排序。在编辑中,我将排序放在最后,以便所有帖子都得到排序
    • 我认为这可行,但有没有办法让 .map((band) 的“band”参数形式进入 convertPost(post, band) 函数?“band”不再存在在代码的那个点的范围内。我首先尝试了这种格式,但是由于 convertPost 函数需要带才能运行......我认为这是错误的方法吗?
    • @Adam Jeliński 有正确的想法。当我看到他的回答时,我正在转换我的代码。
    猜你喜欢
    • 2021-11-25
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2022-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多