首页 > 解决方案 > 在父组件中使用 fetch 传递给子组件

问题描述

在我的 React 应用程序中,我无法fetch使用父组件的状态获取从父组件调用返回到子组件的数据。

我相信我正在遵循标准做法,但它不起作用。

这是我的父组件的摘录。

class TasksView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            bus: null
        }

        this.handleBusLinkClicked = this.handleBusLinkClicked.bind(this);
        this.getBusDetailView = this.getBusDetailView.bind(this);
    }

{*/ called when a button is clicked /*}
    getBusDetailView(bus_pk) {
        const response =
            fetch("/bus_detail_view/" + bus_pk + "/")
                .then(response => response.json())
                .then(data => {
                        this.setState({
                            bus: data.vehicle
                        })
                    }
                );
    }
        render() {
             return (
                <ChargerBusModal bus={this.state.bus}/>
        )
    }

这是我的子组件的摘录:

export class ChargerBusModal extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
            return (
                <Modal show={this.props.show} className={"fade fade-scale charger-detail-modal zoomIn"}
                       id={"bus-detail-modal"}
                       tabIndex={"-1"}>
                    <Modal.Header closeButton>
                        <Modal.Title id={"modal-title"}> Bus Details
                        </Modal.Title>
                    </Modal.Header>
                    <Modal.Body id={"modalBody"}>
                            <BusDetailContext.Provider value={{
                                bus: this.props.bus}}>
                                <Row className={"align-items-center"}>
                                    <Col>
                                        <BusModalInformation/>
                                    </Col>
                                </Row>
                            </BusDetailContext.Provider>

                    </Modal.Body>
                    <Modal.Footer>
                        <Button variant={"secondary"} dataDismiss={"modal"} onClick={this.props.onHide}>Close</Button>
                        <Button variant={"primary"}> Save Changes </Button>
                    </Modal.Footer>
                </Modal>
            )
        }
    }
}

问题是,在子组件中getBusDetailView(bus_pk)调用和this.state.bus设置this.props.bus的时间始终为空。我希望它是父组件的值this.state.bus,但事实并非如此。我确认data.vehicle不为空。

你知道发生了什么吗?

标签: reactjs

解决方案


this.props.state.bus- 你试过这个吗?

我知道这已经一年多了;但是,当我发现这个问题时,我是一个初学者并且遇到了类似的问题(将状态从父组件传递到子组件)。就我而言,在子组件上我必须使用this.props.state& 然后是父状态中的相关对象或元素。

版主:请酌情修改或删除。


推荐阅读