Получить конкретные данные из API ReactJS - PullRequest
0 голосов
/ 22 октября 2018

Я пытаюсь получить определенные данные из API, что-то вроде этого: у меня есть этот JSON после ответа:

{
    "id": 5,
    "url": "http://127.0.0.1:8000/api/article/5/",
    "title": "Obama Offers Hopeful Vision While Nothing Nation's Fears",
    "description": "Obama Offers Hopeful Vision While Nothing Nation's Fears",
    "category": [
        "http://127.0.0.1:8000/api/category/1/"
    ],
    "image": "http://127.0.0.1:8000/media/article_image/news_01_3MT46Rk.jpg"
},
{
    "id": 6,
    "url": "http://127.0.0.1:8000/api/article/6/",
    "title": "NASA Formalizes Efforts To Protect Earth From Asteroids",
    "description": "Last week, NASA annouced a new program called the Planetary Defense Coordination Office (PDCO) which will coordinate NASA's efforts for detecting and tracking near-Earth objects (NEOs), If a large object comes hurting toward our planet...",
    "category": [
        "http://127.0.0.1:8000/api/category/4/"
    ],
    "image": "http://127.0.0.1:8000/media/article_image/news_03_EOUms51.jpg"
},
{
    "id": 7,
    "url": "http://127.0.0.1:8000/api/article/7/",
    "title": "Didi Kuaidi, The Company Beating Uber In China, Opens Its API To Third Party Apps",
    "description": "One day after Uber updated its API to add 'content experiences' for passengers, the U.S company's biggest rival - Didi Kuadii in China - has opened its own platform up by releasing an SDK for developoers and third-parties",
    "category": [
        "http://127.0.0.1:8000/api/category/3/"
    ],
    "image": "http://127.0.0.1:8000/media/article_image/news_02_l5zY4HJ.jpg"
}

И в этом API у меня есть дочерний элемент, названный Category:

 {
    "id": 1,
    "url": "http://127.0.0.1:8000/api/category/1/",
    "name": "POLITICS"
},
{
    "id": 2,
    "url": "http://127.0.0.1:8000/api/category/2/",
    "name": "BUSINESS"
},
{
    "id": 3,
    "url": "http://127.0.0.1:8000/api/category/3/",
    "name": "TECH"
},
{
    "id": 4,
    "url": "http://127.0.0.1:8000/api/category/4/",
    "name": "SCIENCE"
},
{
    "id": 5,
    "url": "http://127.0.0.1:8000/api/category/5/",
    "name": "SPORTS"
}

Я хочу сделать так, чтобы мои статьи отображались в категории ПОЛИТИКА, но я бы не знал, как это сделать. Вот что я сделал до сих пор.

Метод дляполучить json:

getItems() {
    this.setState({ 'isLoading': true });

    fetch('http://127.0.0.1:8000/api/article/')
        .then(results => {
            if (results.ok) {
                return results.json();
            } else {
                throw new Error('Something went wrong ...');
            }
        })
        .then(results => this.setState({ 'items': results, 'isLoading': false }))
        .catch(error => this.setState({ error, isLoading: false }));
}

Мой метод рендеринга:

render() {
    const { isLoading, error } = this.state;

    if (error) {
        return <p>{error.message}</p>;
    }

    if (isLoading) {
        return <p>Loading ...</p>;
    }
    return (
        <ul>
            {this.state.items.map(function (item, index) {
                console.log(item.category.indexOf("1") != 01)
                if (item.category === 1){
                    return <ContentItem item={item} key={index} />
                }
            })}
        </ul>
    );
}

РЕДАКТИРОВАТЬ: Вывод из console.log (элемент) в рендеринг:

{id: 5, title: "Obama Offers Hopeful Vision While Nothing Nation's Fears", description: "Obama Offers Hopeful Vision While Nothing Nation's Fears", category: Array(1), image: "http://127.0.0.1:8000/media/article_image/news_01_3MT46Rk.jpg"}
category: Array(1)
    0: 1
    length: 1
    __proto__: Array(0)
description: "Obama Offers Hopeful Vision While Nothing Nation's Fears"
id: 5
image: "http://127.0.0.1:8000/media/article_image/news_01_3MT46Rk.jpg"
title: "Obama Offers Hopeful Vision While Nothing Nation's Fears"
__proto__: Object

1 Ответ

0 голосов
/ 22 октября 2018

То, что вы НЕ делаете, это фильтрация по id ,

if (item.category === 1){ //You need to add .id here
    return <ContentItem item={item} key={index} />
}

примерно так:

if (item.category.id === 1){ //.id
    return <ContentItem item={item} key={index} />
}

Что вы делаете неправильно, так это то, что выпроверка всего объекта на соответствие условию === 1 вместо свойства id объекта.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...