0

我已经尝试了很多教程,到目前为止,我可以显示项目并了解一点 React。

URL结构是

/works/2

2的查询字符串存储在里面pageID

然后我触发 ajax 调用并过滤数据库以仅显示该数据.find()

这是WorksPage.js列出公司工作组合项目的文件。

import React, { Component } from 'react';
import axios from 'axios';
import './index.css';

class WorksPage extends Component {

    constructor(props) {
        super(props);
        this.state = {itemList: []};
    }

    componentWillMount(){
        const pageID = this.props.match.params.page;
        axios.get('/api/works.json').then(function(response){
            const result = response.data.find(i => i.id === pageID);
            this.setState({ isLoaded: true, itemList: result });
        }.bind(this));
    }

    componentDidMount() {
        window.scrollTo(0, 0);
    }

    render(){
        return(

            <div className="workListing pageWrapper">
                <section className="workListing-process">
                    <div className="smcontainer center txtc">
                     {this.state.itemList}
                     App Type: {this.state.itemList.sub}

                     App cars: {this.state.itemList.cars.map((car, i) =>

                      <div key={i}>
                        {car}
                      </div>

                    )}

                    </div>
                </section>
            </div>
        )
    }

}


export default WorksPage;

我的 JSONworks.json

[{
    "id": 0,
    "img": "/images/slider.jpg",
    "header": "GPS Module",
    "sub": "iOS",
    "link": "/works/0",
    "cars":[ "Ford", "BMW", "Fiat" ]
}{
    "id": 1,
    "img": "/images/map-slider.jpg",
    "header": "GPS Mapping Vectors",
    "sub": "iOS",
    "link": "/works/1",
    "cars":[  ]
},{
    "id": 2,
    "img": "/images/slider.jpg",
    "header": "GPS Module",
    "sub": "Android",
    "link": "/works/2",
    "cars":[ "Ferrari", "BMW", "Land Rover" ]
}]

到目前为止,{this.state.itemList}返回空白。汽车列表循环也不起作用。Console.log 将返回result如果我在之后执行 console.log 的数据this.setState

4

2 回答 2

1

首先,不要使用 componentWillMount,它既不推荐使用也不意味着调用 API。请改用 componentDidMount。

我认为问题是pageID字符串和id数字,因此没有匹配。pageID在比较之前尝试转换为数字。

const pageID = parseInt(this.props.match.params.page, 10);
于 2018-08-21T06:30:11.323 回答
0

您在回调函数中使用“this”关键字,它指的是回调本身而不是组件。并且还使用componentDidmount,不再使用componenwillmount。看这里:componentWillMount

用这个 :

componentDidMount(){
        let that = this;
        const pageID = this.props.match.params.page;
        axios.get('/api/works.json').then(function(response){
            const result = response.data.find(i => i.id === pageID);
            that.setState({ isLoaded: true, itemList: result });
        };
    }
于 2018-08-21T06:25:22.470 回答