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)

我已经将json文件存储在公共文件夹中,如下所示---

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])}))
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...