gpt4 book ai didi

javascript - Array.map() 不渲染 React 组件

转载 作者:行者123 更新时间:2023-12-03 17:11:56 29 4
gpt4 key购买 nike

我遇到一个问题,我试图将数组的数据传递给卡片组件,但它没有出现在页面上,卡片组件自行正常呈现:

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

我将数组作为 props 从父页面组件传递,数据通过 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 作为后端。提前致谢。

最佳答案

当你使用 const [News] = React.useState([]) 时,你对 News 所做的任何更改都不会反射(reflect)在你的 React 应用程序中,因为 mutating 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'])

关于javascript - Array.map() 不渲染 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60231378/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com