Array.map()不渲染React组件

时间:2020-02-14 17:59:41

标签: javascript arrays reactjs

我在尝试渲染将数组的数据传递给card组件时遇到问题,但是它没有出现在页面上,card组件通常单独呈现:

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()显示数据确实存在

enter image description here

并且我从父页面组件将数组作为prop传递,数据通过useEffect中的flamelink 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);

我将Firebase用作与Flamelink结合使用的CMS后端。 预先感谢。

2 个答案:

答案 0 :(得分:5)

使用const [News] = React.useState([])时,对News所做的任何更改都不会反映在您的React应用程序中,因为突变News不会更新组件的状态。如果要更新News的状态,则需要使用React.useState提供的状态分配功能。尝试以下方法:

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

// We can't use News.push('Some news'), but we can update News this way:
updateNews([...News, 'Some news'])

答案 1 :(得分:1)

    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);

我建议使用驼峰大小写变量:

const [stateVariable, setStateVariable] = useState();

https://reactjs.org/docs/hooks-state.html)并将[]添加到依赖项的useEffect数组中。这样可以确保useEffect仅触发一次。希望这会有所帮助。