javascript - Array.map() 不渲染 React 组件
问题描述
我遇到了一个问题,我试图将数组的数据传递给卡片组件,但它没有出现在页面上,卡片组件通常会自行呈现:
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() 显示数据确实存在
我将数组作为来自父页面组件的道具传递,数据通过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 作为后端,结合了 CMS 的 Flamelink。提前致谢。
解决方案
当您使用 时const [News] = React.useState([])
,您所做的任何更改News
都不会反映在您的 React 应用程序中,因为 mutatingNews
不会更新组件的状态。如果要更新 的状态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'])
推荐阅读
- https - 如何将我的 Google 域与我的 Google Cloud DNS 关联?
- unit-testing - AutoMapper 的 AssertConfigurationIsValid 和 EF 导航属性
- python - 如何在熊猫中使用就地保存修改?
- firebase - React Native Firebase Android 总是崩溃 0.61
- c - 如何在 C 中同时接受整数和字符串?
- c# - 无法分配给从 VBA 消耗的 C# 类中的 Hashtable 项
- excel - Excel:定义一个 VBA 函数来缩短 PERCENTRANK
- java - java.lang.IllegalStateException:指定的孩子已经有一个父母。您必须先在孩子的父母上调用 removeView()
- ios - 当用户填写一些文本字段时如何更新 UILabel 的文本
- javascript - 如何在点击时传输输入值