@bpGusar
*spoiler*

Почему в данном примере не передается state как props в дочерний компонент?

Родительский компонент:
import React, { Component } from 'react';
import { ENV } from './ENV'
import { Segment, Header, Label, Divider, Icon } from 'semantic-ui-react'

import Samecatnews from './SameCatNews'

export default class FullNews extends Component {
    state = {
        newsInfo: [],
        idCatSame: 0,
        isLoading: true
    }
    getNewsInfo = () => {
        fetch(`${ENV.API_PROT}${ENV.API_LINK}/api/${ENV.API_VER_GLOBAL}/news/${this.props.newsId}`)
            .then(response => response.json())
            .then(json => {
                console.log(json);
                this.setState({
                    newsInfo: json.data,
                    idCatSame: json.data.id_category_news,
                    isLoading: false
                })
                console.log(this.state.newsInfo);
            });
    }

    componentDidMount() {
        this.getNewsInfo()
    }
    render() {
        return (
            <div>
                <Segment>
                    <Header as='h1'>{this.state.newsInfo.title}</Header>
                    <Label><Icon name='time' /> {this.state.newsInfo.date_post}</Label>
                    <Label><Icon name='list layout' /> {this.state.newsInfo.category_name}</Label>
                    <Divider section />
                    <p>{this.state.newsInfo.short_text}</p>
                    <Divider section />
                    <p>{this.state.newsInfo.full_news}</p>
                </Segment>
                <Segment>
                    <Samecatnews idcat={this.state.idCatSame} />
                </Segment>
            </div>
        );
    }
}


Дочерний:
import React, { Component } from 'react';
import { ENV } from './ENV'
import { Card, Dimmer, Loader, Image } from 'semantic-ui-react'

export default class Samecatnews extends Component {
    state = {
        sameNews: [],
        isLoading: true
    }

    getSameNewsInCat = () => {
        fetch(`${ENV.API_PROT}${ENV.API_LINK}/api/${ENV.API_VER_GLOBAL}/categories/${this.props.idcat}`)
            .then(response => response.json())
            .then(json => { 
                console.log(json);
                this.setState({
                    sameNews: json.data,
                    isLoading: false
                });
                console.log(this.state.sameNews);
            });
    }

    componentWillReceiveProps() {
        console.log(this.props.idcat)
        this.getSameNewsInCat()
    }

    render() {
        let sameCatContent;
        if (this.state.isLoading) {
            sameCatContent = <div>
                <Dimmer active inverted>
                    <Loader inverted>Загрузка новостей</Loader>
                </Dimmer>
                <Image src='https://react.semantic-ui.com/assets/images/wireframe/short-paragraph.png' />
            </div>
        } else {
            sameCatContent = this.state.sameNews.map((News, i) => (
                <Card key={i}>
                    <Card.Content>
                        <Image floated='right' size='mini' src={News.image_news} />
                        <Card.Header>
                            {News.title}
                        </Card.Header>
                        <Card.Meta>
                            {News.category_name}
                        </Card.Meta>
                        <Card.Description>
                            {News.short_text}
                        </Card.Description>
                    </Card.Content>
                </Card>
            ))
        }
        return (
            <div>
                {sameCatContent}
            </div>
        );
    }
}


Если отправлять в props например вот так idcat="1" то всё нормально передается, а если передавать state то он не передается.

В чем тут может быть дело?
  • Вопрос задан
  • 167 просмотров
Решения вопроса 1
RomReed
@RomReed
JavaScript, Flutter, ReactNative, Redux, Firebase
componentWillReceiveProps(nextProps) {
        console.log("nextProps.idcat",nextProps.idcat)
if (nextProps.idcat!==undefined){
fetch(`${ENV.API_PROT}${ENV.API_LINK}/api/${ENV.API_VER_GLOBAL}/categories/${nextProps.idcat}`)
            .then(response => response.json())
            .then(json => { 
                console.log(json);
                this.setState({
                    sameNews: json.data,
                    isLoading: false
                });
                console.log(this.state.sameNews);
            });
}
      
    }
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы