Реквизиты дочернего компонента не обновляются - PullRequest
0 голосов
/ 24 апреля 2020

У меня есть компонент реагирования, который мы называем условным на основе флага.

В ComplianceCards js - я разделил функцию на основе флага runTriggered.

runTriggered ? UpdateCards() : createCards()

ParentComponent ComplianceCards - когда идет внутрь createCards функция все работает нормально, но когда вызывается UpdateCard(), я вижу последние значения, которые я передаю, но в дочернем компоненте все равно отображаются старые значения реквизита.

const UpdateCards = () => {
            let view;
            /**
             * @param {*} deviceId
             * get the compliance details
             */

            let agag = getComplianceDetails(this.props.deviceId)
            .then(parsedData => {
                if (parsedData) {
                    return parsedData;
                }
                else {
                    console.log ("This function is not returning anything. Let's check why!")
                }
            })
            .catch((error)=>{
                console.log ("Let's see what's going on here -> ", error);
            });


            agag.then(data => {
                console.log("agag data", data);
                if (data) {
                    this.setState({
                        updatedCardData: data
                    });

                    const { updatedCardData } = this.state
                    if (updatedCardData) {
                        console.log("if come inside");
                        view = (
                            <div>
                                <DnxCardLayout name="cardlayout" style={{ padding: "5px" }}>
                                    <div className="cards_flex_container">
                                        {updatedCardData &&
                                            updatedCardData.map(newCard => {
                                                return (
                                                    <ComplianceCard
                                                        cardData={newCard}
                                                        key={newCard.complianceType}
                                                        handleClick={this._handleClick}
                                                        storeArchiveData={this.storeArchiveData}
                                                    />
                                                );
                                            })}
                                    </div>
                                </DnxCardLayout>
                            </div>
                        );
                        return view;
                    } else {
                        console.log("updatedCardData else come inside");
                    }
                } else {
                    console.log("else come inside");
                }
            })
            .catch((error)=>{
                console.log ("Let's see what's going on here -> ", error);
            });
        };

когда UpdateCards () вызывает мою консольную распечатку -

agag data `data`
ComplianceCards.js:504 if come inside

Здесь я вижу, что данные - это последнее обновленное значение, но внутри компонентов s \ child это старые значения или реквизиты.

My Родительский компонент ComplianceCards -

export default class ComplianceCards extends Component {

    /**
     * Constructor
     * @param {} props
     */
    constructor(props) {
        super(props);
        this.state = {
            // some states
        };
    }

    /**
     * Component DidMount
     */
    componentDidMount() {
    }

    /**
     * Component will un-mount
     */
    componentWillUnmount() {
    }

    /**
     * render function
     */
    render() {
    }
}

Я провел рефакторинг на основе комментариев и ясного понимания. Я надеюсь, что это поможет.

Это код ComplianceCard моего дочернего компонента -

import React, { Component } from "react";
// some other dependencies

export default class ComplianceCard extends Component {
    constructor(props) {
        super(props);
        this.state = {
            latestArchivedVersion: null,
            networkProfiles: null,
            showImageLoader:false,
            showConfigLoader:false
        };
    }

    /**
     * Get data for each complianceType
     */
    componentDidMount() {
        let { cardData, storeArchiveData } = this.props;
        const complianceType = cardData.complianceType;
        const deviceUuid = cardData.deviceUuid;
        if (complianceType == labels.runningConfig) {
            this.setState( {
                showConfigLoader:true
            })
            getArchiveConfigDetails(deviceUuid).then(data => {
                if (data) {
                    this.setState({
                        latestArchivedVersion: data[data.length - 1]
                    });
                    if (storeArchiveData) {
                        storeArchiveData(data);
                    }
                    this.setState( {
                        showConfigLoader:false
                    })
                }
            });
        } else if (complianceType == labels.networkProfile) {
            // TODO, do we really need this? we need to re-trigger the details api to get all NETWORK_PROFILE data
            getComplianceDetails(deviceUuid, {
                complianceType: labels.networkProfile
            }).then(data => {
                if (data) {
                    this.setState({
                        networkProfiles: [...data]
                    });
                }
            });
        } else if (complianceType == labels.softwareImage) {
            this.setState( { 
                showImageLoader: true
            });
            getImageDetails(deviceUuid).then(data => {
                if (data) {
                    this.setState({
                        imageDetails: data,
                        showImageLoader: false
                    });
                }
            });
        }
    }

    componentDidUpdate(prevProps) {
        if (prevProps.cardData !== this.props.cardData) {
            let { cardData } = this.props;
        }
    }

    componentWillReceiveProps(nextProps) {
        this.setState({ data: nextProps.data });  
      }

    /**
     * Component will un-mount
     */
    componentWillUnmount() {

    }

    /**
     * Handles click event
     * @param {*} target
     */
    handleClick = target => {
        let { cardData, handleClick } = this.props;
        const complianceType = cardData.complianceType;
        handleClick(complianceType, cardData);
    };


    /**
     * Component render function
     */
    render() {
        let { cardData } = this.props;
        // render function code
    }
}

, пожалуйста, укажите на проблему, Спасибо ..

Ответы [ 2 ]

0 голосов
/ 24 апреля 2020
let agag = getComplianceDetails(this.props.deviceId)
    .then(data => data.json())
    .then(parsedData =>{
        if (parsedData) {
            return parsedData;
        }
        else{
            console.log ("This function is not returning anything. Let's check why!")
        }
    })
    .catch((error)=>{
        console.log ("Let's see what's going on here -> ", error);
    });
0 голосов
/ 24 апреля 2020

Вы ничего не возвращаете из условия if, поэтому React не начнет рендеринг этих карт.

const createCards = runTriggered => {
            let newCards, view = null;
            /**
             * @param {*} deviceId
             * get the compliance details
             */
            let agag = getComplianceDetails(this.props.deviceId).then(data => {
                if (data) {
                    return data;
                }
                // .then afterwards will fail if no data is present
            });
            if (runTriggered) {
                // No return here, assuming createCards is treated as a promise you can try:
                // return agag.then(...
                agag.then(data => {
                    newCards = data;
                    view = (...);
                    return view;
                });
            } else {
                view = (...);
                return view;
            }
        };
    ```
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...