如何解决React.js未显示从状态生成的动态数据
我在遍历reactjs组件上的javascript对象数组时遇到问题。 chrome浏览器检查视图从console.log提供此输出---
0: {id: 1,title: "This is a post 1"}
1: {id: 2,title: "This is a post 2"}
2: {id: 3,title: "This is a post 3"}
3: {id: 4,title: "This is a post 4"}
4: {id: 5,title: "This is a post 5"}
length: 5
__proto__: Array(0)
public
--post-data
----posts.json
----1.json
----2.json
----3.json
----4.json
----5.json
posts.json文件---
[1,2,3,4,5]
1.json文件---
{
"id": 1,"title": "This is a post 1"
}
import React,{ Fragment,Component } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import {
Container,Row,Col,Jumbotron
} from 'reactstrap';
class HomePage extends Component {
state = { posts: [] }
getPost(path) {
axios.get(path)
.then(res => (this.state.posts.push(res.data)));
}
componentDidMount() {
axios.get('./post-data/posts.json')
.then(response => response.data.map((value) => (
this.getPost('./post-data/' + value + '.json')
)));
console.log(this.state.posts);
}
render() {
const listItems = this.state.posts.map((data,key) =>
<Col lg={{ size: 4 }} className="mb-3">{key}</Col>
);
return (
<Fragment>
{this.state.posts ? <section>
<Container>
<Row>
{listItems}
</Row>
</Container>
</section> : <p>No posts found!</p>}
</Fragment>
)
}
}
export default HomePage;
但是屏幕上没有任何显示。请帮帮我!
解决方法
我认为您的问题是您的回报表中缺少括号,请尝试:
return (
<Fragment>
{this.state.posts ? (<section>
<Container>
<Row>
{listItems}
</Row>
</Container>
</section>) : (<p>No posts found!</p>)}
</Fragment>
)
基本上,区别在于您的有条件回报,每个部分都用括号condition ? (return 1) : (return 2)
标记
此外,当您尝试直接在this.getPost()
中更改状态时,您可能会遇到问题,应该使用this.state.posts.push(something)
而不是this.setState()
来写{{1} }。
您需要使用setState,否则将不会调用重新渲染。
将getPost方法更改为此:
getPost(path) {
axios.get(path)
.then(res => this.setState({posts: this.state.posts.concat([res.data])}))
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。