简体   繁体   English

从React Fetch调用组件方法

[英]Call component method from React fetch

I have a Component called SeanceManager . 我有一个名为SeanceManagerComponent And in that Component I have a method that requests data from backend using fetch . 在该Component中,我有一个method可以使用fetch从后端请求数据。

class SeanceManager extends React.Component {

    constructor(...args) {
        super(...args);

        this.state = {
            addSeanceModalShow: false,
            seances: [],
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleDeleteUser = this.handleDeleteUser.bind(this);
        this.fetchSeance = this.fetchSeance.bind(this);
    }

    componentDidMount() {
        this.fetchSeance()
    }



    fetchSeance = () => {
        fetch("/seances")
            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        addSeanceModalShow: false,
                        seances: result
                    });
                    console.log("Fetchime: "+this.state.seances);
                },

                (error) => {
                    this.setState({
                        addSeanceModalShow: true,
                        error
                    });
                }
            )
        console.log("l6pp: "+this.state.seances);
    }

    handleSubmit = (event, devices, interval, startDate, endDate) => {
        event.preventDefault();
        if (devices && interval && startDate && endDate) {
            var data = { devices: devices, interval: interval, startDate: startDate, endDate: endDate };
            fetch('/create', {
                method: 'post',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            }).then(function (response) {
                console.log(response)
                //TODO: Should handle here somehow ?
                // return response;
            }).then(function (data) {
                // console.log(data);
                //------------------------Method crashing here-----------
                this.fetchSeance();
               //---------------------------------------------------
            });

            // this.fetchSeance();
        }
    };

    handleDeleteUser = id => {
        fetch('/delete/'+id, {
            method: 'delete',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(id)
        }).then(function (response) {
            console.log("Kustumise response");
            console.log(response);
            //TODO: Should handle here somehow ?
            // return response;
        }).then(function (data) {
            // console.log(data);
        });
        this.fetchSeance();
        this.setState({state: this.state});
    };

    render() {
        let addSeanceModalClose = () => this.setState({ addSeanceModalShow: false });

        return (

            <MDBRow>
                <MDBCol className="col d-flex justify-content-center">
                    <MDBCard className="card col-md-6">
                        <MDBCardBody>
                            <div className="add-button-parent">
                                <MDBBtn className="add-button-child" color="cyan"
                                        onClick={() => this.setState({ addSeanceModalShow: true })}>
                                    Lisa uus seanss
                                </MDBBtn>
                            </div>

                            <form>
                                <AddSeanceFormModal
                                    show={this.state.addSeanceModalShow}
                                    handleSubmit={this.handleSubmit}
                                    onHide={addSeanceModalClose}
                                />
                                {/*{this.addToSeanceList()}*/}
                                <div className="card scrollbar-ripe-malinka ">
                                    <div className="row ">
                                        <div className="container-fluid">
                                            <div className="card-body">
                                                <h4 id="section1"><strong>Aktiivsed seansid</strong></h4>
                                                <Seances
                                                    handleDeleteUser={this.handleDeleteUser}
                                                    seances={this.state.seances} />

                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </MDBCardBody>
                    </MDBCard>
                </MDBCol>
            </MDBRow>
        );
    }

};

export default SeanceManager;

But when calling method this.fetchSeance() inside of the fetch method I get the: 但是在fetch方法内部调用方法this.fetchSeance() ,我得到了:

Unhandled Rejection (TypeError): Cannot read property 'fetchSeance' of undefined

How can I call the method from within the fetch? 如何从提取中调用方法?

You've used 你用过

}).then(function (data) {
                // console.log(data);
                //------------------------Method crashing here-----------
                this.fetchSeance();
               //---------------------------------------------------
            });

when you should have used an arrow function to keep this the same as the outer scope. 当你应该使用箭头功能,以保持this一样的外部范围。

}).then((data) => {
                // console.log(data);
                //------------------------Method crashing here-----------
                this.fetchSeance();
               //---------------------------------------------------
            });

Again change: 再次更改:

}).then(function (data) {

to: 至:

}).then((data) => {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM