1

这是我的父代码:

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?或者这段代码还有其他问题吗?以及如何避免子组件中未定义标签的问题?

干杯

4

2 回答 2

2

为避免您的问题,在具有任何有用值之前,您不应该渲染您的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} />
        );
    }
}
于 2020-05-03T19:31:44.930 回答
0

您的子组件肯定会使用空的“标签”数组作为道具进行渲染。然后,当 getTags() 返回数据时,新填充的标签数组将作为道具传递给孩子,强制孩子用新数据重新渲染。

它应该是空数组,而不是“未定义”。您可能会检查您的 getTags() 方法和您正在调用的 API,以确保您没有从那里得到“未定义”。

componentWillReceiveProps 是遗留的,不应使用。有关详细信息,请参阅 React 文档中的以下链接:https ://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

如果您因更改道具而需要执行副作用,该文档将指导您如何做。

现在唯一的事情是 componentWillReceiveProps 是为 props 设置本地状态,这完全是多余的。您还需要在那里做其他事情吗?

于 2020-05-03T19:41:44.733 回答