带有 axios 的 reactjs “无法读取未定义的 属性 'map'”

reactjs with axios “Cannot read property 'map' of undefined`”

我在使用 React 时乱七八糟,在从 本地文件 localhost 读取 json 时出现此错误。我检查了其他问题,但没有得到任何结果。我已经从 chrome 应用商店安装了 React 开发工具并检查了错误,所以我没有收到跨源错误。

代码如下:

class Content extends React.Component {
    constructor(){
        super();
        this.state={
            json: {
                categories: []          
            }
        };
    }
    componentWillMount(){

        var _this = this;
        var loc = window.location.pathname;
        var dir = loc.substring(0, loc.lastIndexOf('/'));

        this.serverRequest = 
            axios
            .get(dir+"/data.json")
            .then(function(result) {    
            // we got it!
                _this.setState({
                    json:result 
                });
            });
    }
    render() {
        var title =  <a>{this.state.json.title}</a>;
        return (
            <div>
                <h2>Content</h2>
                <h3>{title}</h3>

                {this.state.json.categories.map(function(item) {
                    return (
                        <div key={item.categoryID} className="category">
                            <div> {item.categoryName} </div>  
                            <div> {item.categoryDescridivtion} </div> 
                            <div> {item.videosCount} </div> 
                        </div>
                    );
                })}
            </div>
        );
    }
}

这是JSON:

{
    "categories": [{
        "categoryID": "294",
        "parentID": "304",
        "subjectID": "7",
        "categoryName": "Apps and Side Dishes (Laura)",
        "categoryDescription": "Learn to make amazing appetizers and side dishes with Laura in the Kitchen.",
        "videosCount": "101",
        "forumCategoryID": "163"
    }, {
        "categoryID": "285",
        "parentID": "304",
        "subjectID": "7",
        "categoryName": "Side Dishes",
        "categoryDescription": "Side dish recipes for salads, vegetables, sauces with Hilah cooking.",
        "videosCount": "38",
        "forumCategoryID": "163"
    }, {
        "categoryID": "337",
        "parentID": "304",
        "subjectID": "7",
        "categoryName": "Side Dishes (bt)",
        "categoryDescription": "Side dish recipes with Byron Talbott.",
        "videosCount": "5",
        "forumCategoryID": "163"
    }, {
        "categoryID": "301",
        "parentID": "304",
        "subjectID": "7",
        "categoryName": "Side Dishes for Barbecue",
        "categoryDescription": "Barbecue side dish recipes done on the grill by the BBQ Pit Boys!",
        "videosCount": "43",
        "forumCategoryID": "163"
    }, {
        "categoryID": "297",
        "parentID": "304",
        "subjectID": "7",
        "categoryName": "Soups and Salads (Laura)",
        "categoryDescription": "Looking for the perfect recipe to start your meal? Or are you looking to eat something on the lighter side? These are sure to have you covered!",
        "videosCount": "70",
        "forumCategoryID": "163"
    }],

    "title": "Title page"
}

这里是调试控制台关于 axios 调试控制台结果的输出:

您的控制台屏幕截图清楚地说明了为什么它不起作用:result 没有 categories 属性。 result.data 具有 categories,axios 将结果包装在各种信封中,为您提供有关请求的信息(configheadersstatus 等)并提供实际数据 data。所以:

this.serverRequest = 
    axios
    .get(dir+"/data.json")
    .then(function(result) {    
    // we got it!
        _this.setState({
            json:result.data   // ***
        });
    });

示例:

class Content extends React.Component {
    constructor(){
        super();
        this.state={
            json: {
                categories: []          
            }
        };
    }
    componentWillMount(){
        
        var _this = this;
        var loc = window.location.pathname;
        var dir = loc.substring(0, loc.lastIndexOf('/'));
        
        this.serverRequest = 
            axios
            .get(dir+"/data.json")
            .then(function(result) {    
            // we got it!
                console.log(result); // So you can check it against your image
                _this.setState({
                    json:result.data
                });
            });
    }
    render() {
        var title =  <a>{this.state.json.title}</a>;
        return (
            <div>
                <h2>Content</h2>
                <h3>{title}</h3>
                
                {this.state.json.categories.map(function(item) {
                    return (
                        <div key={item.categoryID} className="category">
                            <div> {item.categoryName} </div>  
                            <div> {item.categoryDescridivtion} </div> 
                            <div> {item.videosCount} </div> 
                        </div>
                    );
                })}
            </div>
        );
    }
}

const data = {
    "config": {
        "some": "stuff"
    },
    data: {
        "categories": [{
            "categoryID": "294",
            "parentID": "304",
            "subjectID": "7",
            "categoryName": "Apps and Side Dishes (Laura)",
            "categoryDescription": "Learn to make amazing appetizers and side dishes with Laura in the Kitchen.",
            "videosCount": "101",
            "forumCategoryID": "163"
        }, {
            "categoryID": "285",
            "parentID": "304",
            "subjectID": "7",
            "categoryName": "Side Dishes",
            "categoryDescription": "Side dish recipes for salads, vegetables, sauces with Hilah cooking.",
            "videosCount": "38",
            "forumCategoryID": "163"
        }, {
            "categoryID": "337",
            "parentID": "304",
            "subjectID": "7",
            "categoryName": "Side Dishes (bt)",
            "categoryDescription": "Side dish recipes with Byron Talbott.",
            "videosCount": "5",
            "forumCategoryID": "163"
        }, {
            "categoryID": "301",
            "parentID": "304",
            "subjectID": "7",
            "categoryName": "Side Dishes for Barbecue",
            "categoryDescription": "Barbecue side dish recipes done on the grill by the BBQ Pit Boys!",
            "videosCount": "43",
            "forumCategoryID": "163"
        }, {
            "categoryID": "297",
            "parentID": "304",
            "subjectID": "7",
            "categoryName": "Soups and Salads (Laura)",
            "categoryDescription": "Looking for the perfect recipe to start your meal? Or are you looking to eat something on the lighter side? These are sure to have you covered!",
            "videosCount": "70",
            "forumCategoryID": "163"
        }],

        "title": "Title page"
    },
    "headers": {
        "some": "stuff"
    }
};

const axios = {
    get() {
        return new Promise(resolve => {
            setTimeout(resolve, 100, data);
        });
    }
};

ReactDOM.render(
    <Content />,
    document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>