简体   繁体   English

Array.map() 不渲染 React 组件

[英]Array.map() doesn't render React component

I am having a problem where i'm trying to render pass an array's data to a card component but it doesn't appear on the page, the card component renders normally on its own:我遇到了一个问题,我试图将数组的数据渲染传递给卡片组件,但它没有出现在页面上,卡片组件会自行正常呈现:

import React, { Component } from 'react'
import { Container, Grid, Card, Segment, Header } from 'semantic-ui-react';
import ArticleCard from './ArticleCard';


export default class NewsGrid extends Component {
    render() {
        const {News} = this.props
        console.log(News)

        return (
            <div>
                <Container style={{marginTop: '7%'}}>
                <Grid stackable divided >
                    <Grid.Column style={{width: '66.66%'}}>
                        <Card.Group>
                            {
                                News.map(({id, ...otherArticleProps}) => (
                                    <ArticleCard key={id} {...otherArticleProps} />
                                ))
                            }
                        </Card.Group>
                    </Grid.Column>

                </Grid>
            </Container>
            </div>
        )
    }
}

console.log() shows that the data is actually there console.log() 显示数据确实存在

在此处输入图片说明

and i'm passing the array as props from the parent page component, the data is delivered through the flamelink API in useEffect as shown bellow:并且我将数组作为来自父页面组件的道具传递,数据通过 useEffect 中的火焰链接 API 传递,如下所示:

import React, { useEffect, useState } from 'react';
import NewsGrid from '../components/NewsGrid';
import BusinessContainer from '../components/BusinessContainer';
import PolitiqueContainer from './../components/PolitiqueContainer';
import app from '../Firebase';
import { withRouter } from 'react-router-dom';

const Homepage = () => {
    const [News] = useState([])
    const [Business] = useState([])
    const [Politique] = useState([])
    const [Opinion] = useState([])
    const [Blog] = useState([])

    useEffect(() => {
        app.content.get({schemaKey: 'articles',
                        fields: ['title', 'author', 'date', 'thumbnail', 'slug', 'summary', 'category', 'id'],
                        orderBy:{field: 'date',
                        order: 'desc'},
                         })
        .then(articles => {
            for(var propName in articles) {
                const propValue = articles[propName]

                switch(propValue.category) {
                    default :
                        break;
                    case 'News': 
                        News.push(propValue)
                        break;
                    case 'Business': 
                        Business.push(propValue)
                        break;
                    case 'Politique': 
                        Politique.push(propValue)
                        break;
                    case 'Opinion': 
                        Opinion.push(propValue)
                        break;
                    case 'Blog': 
                        Blog.push(propValue)
                        break;

                }
            }
        })
    })


    return (
        <div >
            <NewsGrid  News={News} Opinion={Opinion} Blog={Blog} />
            <BusinessContainer  content={Business} />
            <PolitiqueContainer  content={Politique} />

        </div>
    );
};

export default withRouter(Homepage);

I am using firebase as a backend combined with Flamelink for the CMS.我使用 firebase 作为后端,结合 Flamelink 用于 CMS。 Thanks in advance.提前致谢。

When you use const [News] = React.useState([]) , any changes you make to News will not be reflected in your React application, since mutating News will not update the state of your component.当您使用const [News] = React.useState([]) ,您对News所做的任何更改都不会反映在您的 React 应用程序中,因为更改News不会更新您组件的状态。 If you want to update the state of News , you need to use the state dispatch function provided by React.useState .如果要更新News的状态,则需要使用React.useState提供的状态调度功能。 Try this instead:试试这个:

const [News, updateNews] = React.useState([])

// We can't use News.push('Some news'), but we can update News this way:
updateNews([...News, 'Some news'])
    import React, { useEffect, useState } from 'react';
    import NewsGrid from '../components/NewsGrid';
    import BusinessContainer from '../components/BusinessContainer';
    import PolitiqueContainer from './../components/PolitiqueContainer';
    import app from '../Firebase';
    import { withRouter } from 'react-router-dom';

    const Homepage = () => {
      const [news, setNews] = useState([]);
      const [business, setBusiness] = useState([]);
      const [politique, setPolitique] = useState([]);

  const [opinion, setOpinion] = useState([]);
  const [blog, setBlog] = useState([]);

  useEffect(() => {
    app.content
      .get({
        schemaKey: 'articles',
        fields: ['title', 'author', 'date', 'thumbnail', 'slug', 'summary', 'category', 'id'],
        orderBy: { field: 'date', order: 'desc' },
      })
      .then(articles => {
        for (let propName in articles) {
          const propValue = articles[propName];

          switch (propValue.category) {
            case 'News':
              setNews(propValue);
              break;
            case 'Business':
              setBusiness(propValue);
              break;
            case 'Politique':
              setPolitique(propValue);
              break;
            case 'Opinion':
              setOpinion(propValue);
              break;
            case 'Blog':
              setBlog(propValue);
              break;
            default:
                break;
          }
        }
      });
  }, []);

  return (
    <div>
      <NewsGrid News={news} Opinion={opinion} Blog={blog} />
      <BusinessContainer content={business} />
      <PolitiqueContainer content={politique} />
    </div>
  );
};

export default withRouter(Homepage);

I would suggest using camel case variables:我建议使用驼峰式大小写变量:

const [stateVariable, setStateVariable] = useState();

( https://reactjs.org/docs/hooks-state.html ) and to add the [] to the useEffect array of dependencies. ( https://reactjs.org/docs/hooks-state.html ) 并将[]添加到依赖项的useEffect数组。 This will ensure that the useEffect will trigger only a single time.这将确保useEffect只会触发一次。 Hope that this helps.希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM