ReactJS获取JSON数据

时间:2016-11-22 19:15:19

标签: json reactjs

您可以找到我的JSON data on this link。我无法做的是从React获取article数据。

我的代码如下。我没有在我的问题中包含JSON get请求代码,因为它并不完全重要。我使用jQuery $ .getJSON方法将fulldata的状态替换为数组。因此,假设数据完全位于fulldata下。

getInitialState:function(){
    return { fulldata: {forthem:[ {articles: [] } ]}  }
},

viewer:function(){
    return (<ul>
            {this.state.fulldata.forthem[0].articles.map(function(makeit, o){
                return <li key={o}>{makeit.article}</li>})}
            </ul>)
},

现有代码允许我做的是获取emjayweb下的第一组文章。但是,如果我将代码修改为this.state.fulldata.forthem[1],则无法在articles下获得第二组cnn。我收到Cannot read property map of undefined错误。

1 个答案:

答案 0 :(得分:1)

试试这个......所以我们不使用外部循环来获取数据,而是使用数组的mapreduce函数。

    const articles = data.forthem.map(item =>
        item.articles.map(article => article)
    ).reduce((list, current) =>
        list.concat(current)
    );

下面的工作示例......

const data = {
    "forthem": [
        {
            "therefore": "emjayweb",
            "theresym": "emj",
            "articles": [
                {
                    "number": "1",
                    "article": "How to Strengthen Your Password",
                    "url": "",
                    "pubdate": ""
                }, {
                    "number": "2",
                    "article": "Second Article",
                    "url": "",
                    "pubdate": ""
                }
            ]
        }, {
            "therefore": "CNN",
            "theresym": "cnn",
            "articles": [
                {
                    "number": "3",
                    "article": "Work It",
                    "url": "",
                    "pubdate": ""
                }
            ]
        }
    ]
};

class MyComponent extends React.Component {
    render() {
        return <div>
            <h2>Articles</h2>
            <ul>
                {this.props.articles.map(item => <li key={item.number}>{item.article}</li>)}
            </ul>
        </div>
    }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            articles: []
        }
    }

    componentWillMount() {
        const articles = data.forthem.map(item =>
            item.articles.map(article => article)
        ).reduce((list, current) =>
            list.concat(current)
        );

        this.setState({ articles });
    }

    render() {
        return <div>
            <h1>React Demo</h1>
            <MyComponent articles={this.state.articles}/>
        </div>
    }
}

ReactDOM.render(<App/>, document.getElementById('root'));
<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>
<div id="root"></div>