javascript - 将 Pros 从 State 传递给 Child

标签 javascript reactjs

我正在从父 React 组件上的 componentDidMount 中的 WebAPI 调用获取数据。我将这些值放入状态中。

当我渲染表单时,我只是使用数据(组件)制作自定义标签,并将标签文本和数据传递给该组件。 (我显示的每个字段都有一个)。我通过 props 将状态中的值传递给子组件。

但我发现我的子组件正在渲染而没有填充数据...因为这似乎发生在 api 调用发生之前。 api 发生,状态被设置,但数据永远不会到达子组件。我认为 Prop 会将更新的状态数据传递给组件。我错了。我应该如何实现这个目标?我想在父组件中加载数据,然后渲染子组件,传入数据。

  componentDidMount() {
        this.loadData();
    }

    loadData() {
        var request = {
            method: 'GET',
            URL: "http://example.com/api/user/profile",
        }

        fetchData(request).then(response => {
            if(response.errorcode != "OK")
            {
                console.log("Bad response from API. Need to redirect!")
            }
            else
            {
                this.setState(
                    {
                        firstname: response.payload.firstname, 
                        surname: response.payload.surname,
                        email: response.payload.email,
                        countryId: response.payload.countryId,
                        countries: response.payload.countries
                    }
                );
            }
        });
    }

    render() {
        return (
            <div>
                <h2>Your Profile</h2>
                <div className="row">
                    <div className="col-xs-6">
                        <DisplayLabel labelText={"Firstname"} data={this.state.firstname} />
                        <DisplayLabel labelText={"Surname"} data={this.state.surname} />
                        <DisplayLabel labelText={"Email Address"} data={this.state.email} />
                        <DisplayLabel labelText={"Country"} data={this.state.countryId} />
                        <div className="form-group row right">
                            <button className="btn btn-primary" onClick={this.openModal}>Edit</button>
                        </div>
                    </div>
                </div>
                <Modal isOpen={this.state.modalIsOpen} onAfterOpen={this.afterOpenModal} style={modalStyle}>
                    <ProfileEditBox closeMeCallback = {this.closeModal} />
                </Modal>
            </div>
        )
    }

我的显示标签组件就是这样。我对此很陌生,只是想制作可重用的组件:

import React, {Component} from 'react';

export default class DisplayLabel extends Component {
    constructor(props)
    {
        super(props);
        this.state = {
            labelText: this.props.labelText,
            data: this.props.data
        }
        console.log(this.state);

    }

    componentDidMount() {
        this.setState({
            labelText: this.props.labelText,
            data: this.props.data
        });
        console.log("ComponentDidMount", this.state);

    }

    render() {
        return (
            <div>
                <div className="row">
                    <div className="col-xs-12">
                        <label className="control-label">{this.state.labelText}</label>
                    </div>
                </div>
                <div className="row">
                    <div className="col-xs-12">
                        &nbsp;&nbsp;<strong><span>{this.state.data}</span></strong>
                    </div>
                </div>
            </div>
        )
    }
}

我需要等待 API 调用完成才能渲染表单吗?

最佳答案

这是 React 中的一个常见问题。我通常尝试使用显示某种加载指示器的模式来解决它。因此,我将在构造函数中像这样初始化您的 state:

    this.state = {
        loading: true
    }

我会更改您的render以检查loading bool:

render() {
    if (this.state.loading) {
        return (<h1>Loading, please wait...</h1>);
    }
    return (
        <div>
            <h2>Your Profile</h2>
            <div className="row">
                <div className="col-xs-6">
                    <DisplayLabel labelText={"Firstname"} data={this.state.firstname} />
                    <DisplayLabel labelText={"Surname"} data={this.state.surname} />
                    <DisplayLabel labelText={"Email Address"} data={this.state.email} />
                    <DisplayLabel labelText={"Country"} data={this.state.countryId} />
                    <div className="form-group row right">
                        <button className="btn btn-primary" onClick={this.openModal}>Edit</button>
                    </div>
                </div>
            </div>
            <Modal isOpen={this.state.modalIsOpen} onAfterOpen={this.afterOpenModal} style={modalStyle}>
                <ProfileEditBox closeMeCallback = {this.closeModal} />
            </Modal>
        </div>
    )
}

然后,您可以在成功提取数据后将 loading 设置为 false,您的表单将正确显示,不会出现任何错误。

(我对此进行了编辑以使用您的父组件而不是 DisplayLabel,因为它在那里更有意义。但是,您的问题中省略了组件名称)。

关于javascript - 将 Pros 从 State 传递给 Child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49321660/

相关文章:

javascript - npm run build 后 React 组件的 onClick 未呈现

reactjs - React 最佳实践中的错误处理

javascript - 对于 GraphQL,声明一个与 GraphQL "class"没有任何明显差异的支持模型 "Type"有什么好处或必要性?

javascript - Highcharts 渲染动画反转?

javascript - jQuery $(...).empty().append(...) 在多次执行后会减慢整个页面的速度

javascript - 使用整数列表的密度图

javascript - 如何在 expo 中添加 Agora.io Android sdk?

javascript - 我可以将 <object> 元素插入到伪类::之前的内容中吗?

javascript - 更新 for 循环中的值/重置 for 循环?

javascript - Reactjs - Formik 表单不会在按下返回键时触发提交