子组件的道具未更新

时间:2020-04-24 04:35:27

标签: javascript reactjs react-lifecycle

我有一个React组件,我们根据标志来调用它。

在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组件中,它是旧的值或道具。

我的父母组件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 :(得分:0)

您不会从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;
            }
        };
    ```

答案 1 :(得分:0)

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);
    });