首页 > 解决方案 > React 道具值未定义

问题描述

这是我的父代码:

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tags: [],
        };
    }
    componentDidMount() {
        this.getTags();
    }

    getTags() {
        //method gets tags from the backend
    }
    render() {
        return <Child tags={this.state.tags} />;
    }
}

这基本上是我的子组件:

export default class Child extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tags: props.tags,
        };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            tags: nextProps.tags,
        });
    }
}

但是当我在组件中的某处控制台日志标签时Child,它是未定义的。也许它是未定义的,因为子组件在父组件调用方法之前被渲染getTags?或者这段代码还有其他问题吗?以及如何避免子组件中未定义标签的问题?

干杯

标签: javascriptreactjsreact-propscomponentwillreceiveprops

解决方案


为避免您的问题,在具有任何有用值之前,您不应该渲染您的Child组件。this.state.tags

这是您如何做到这一点并显示“正在加载...”文本,因此用户不必担心页面损坏。

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tags: [],
        };
    }
    componentDidMount() {
        this.getTags();
    }

    getTags() {
        //method gets tags from the backend
    }
    render() {
        return this.state.tags.length ? (
            'Loading...'
        ) : (
            <Child tags={this.state.tags} />
        );
    }
}

推荐阅读