[英]react matrerial ui Error: Objects are not valid as a React child If you meant to render a collection of children, use an array instead
I am facing the error with the following code and there seems to be no fixes that is solving my issue.我面临以下代码的错误,似乎没有解决我的问题的修复程序。
componentDidMount() { axios.get('http://localhost:8080/home').then((response) => { this.setState({ data: response.data }); }).catch((err) => { console.log(err); }); }
{"data":{"count":{"monthly_blog_count":1,"total_blog_count":1,"monthly_poem_count":0,"total_poem_count":0,"monthly_song_count":0,"total_song_count":0,"monthly_graphics_count":1,"total_graphics_count":1},"latest_graphics":{"link":"ganesha.svg"},"latest_blog":{"title":"test","created":"2021-05-08T07:49:50.000Z","name":"Abhishek Banerjee"},"latest_blog_list":[{"title":"test","created":"2021-05-08T07:49:50.000Z","name":"Abhishek Banerjee"}]}}
<Poems data={data} />
Here's the poem component edited as it's not allowing all code: the base element is card.这是编辑的诗歌组件,因为它不允许所有代码:基本元素是卡片。 I took out code from the poem component since it's complaining not enough text.我从诗歌组件中取出代码,因为它抱怨文本不足。 I have protypes validation on the component as well.我也对组件进行了原型验证。
const Poems = (props) => { const { data: count, 'data.count.total_poem_count': totalPoemCount, 'data.count.monthly_poem_count': monthlyPoemCount, } = props; return ( <Card sx={{ height: '100%' }} {...props} > <Grid item> <Typography color="textPrimary" variant="h3" > { totalPoemCount } </Typography> </Grid> <Typography sx={{ color: green[900], mr: 1 }} variant="body2" > { monthlyPoemCount } </Typography> </card> ); };
Edit编辑
putting { data?.data?.count?.total_poem_count }
works like a charm.放{ data?.data?.count?.total_poem_count }
就像一个魅力。 But the proptypes validation is gone.但是 proptypes 验证已经消失了。 Can anyone suggest me how to get proptypes as well working.谁能建议我如何让道具类型也能正常工作。
Best Practice is to use axios package for fetching api.最佳实践是使用 axios package 来获取 api。
axios.get("http://localhost:8080/home")
.then((response) => {
this.setState({
data: response.data
});
})
.catch((err) => {
console.log(err);
});
passing data to component将数据传递给组件
<Poems data={this.state.data} />
child component子组件
const Poems = ({ data }) => {
const dataToRender = data?.data
return (
<Card
sx={{ height: '100%' }}
{...props}
>
<Grid item>
<Typography
color="textPrimary"
variant="h3"
>
{ dataToRender.count.totalPoemCount }
</Typography>
</Grid>
<Typography
sx={{
color: green[900],
mr: 1
}}
variant="body2"
>
{ dataToRender.count.monthlyPoemCount }
</Typography>
</card>
);
};
< <
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.