发送删除请求后重新呈现反应不起作用

时间:2023-01-15 19:13:40

I have React.js in the front-end and Express.js in the back-end. At the moment I am trying to delete a post from React with a Delete request and it works but I have to go to the url and hit enter before it shows the new list after deleting. I would like the page to re-render without having to hit refresh.

我在前端有React.js,在后端有Express.js。目前我正在尝试使用删除请求删除React中的帖子并且它可以正常工作,但我必须转到URL并在删除之后显示新列表之前按Enter键。我希望页面重新渲染而不必点击刷新。

class Rentals extends Component {

    constructor(props) {
        super(props);
        this.state = {
            completelist: [],
            apiLoaded: false,
        }
        this.conditionalRentList = this.conditionalRentList.bind(this);
        this.handleDeleteButton = this.handleDeleteButton.bind(this);
        this.fetchAllRentals = this.fetchAllRentals.bind(this);
    }

    componentDidMount() {
        this.fetchAllRentals();
    }

    fetchAllRentals() {
        fetch('api/listofrentals')
            .then((res) => {
                return res.json()
            })
            .then((fullrental) => {
                this.setState((prevState) => {
                    return {
                        completelist: fullrental.rentalsData,
                        apiLoaded: true
                    }
                })
            })
    }

    conditionalRentList() {
        if (this.state.apiLoaded === true) {
            return (
                <RentalsComp
                    completelist={this.state.completelist}
                    handleDeleteButton={this.handleDeleteButton}
                />
            );
        } else {
            return <p> Loading </p>
        }
    }

    handleDeleteButton(idToBeDeleted) {
        fetch(`api/listofrentals/${idToBeDeleted}`, {
            method: 'DELETE'
        }).then((res) => {
            if (res.json === 200) {
                this.fetchAllRentals();
            }
        })
    }

}

the function handleDeleteButton should fetch all the listings and render it without having to refresh since it calls the fetchAllRentals function but its not working for some reason.

函数handleDeleteButton应该获取所有列表并呈现它而不必刷新,因为它调用fetchAllRentals函数但由于某些原因它不起作用。

1 个解决方案

#1


0  

Was supposed to be resp.status===200 but was doing resp.json===200 instead.

本来应该是resp.status === 200但是做了resp.json === 200而不是。

#1


0  

Was supposed to be resp.status===200 but was doing resp.json===200 instead.

本来应该是resp.status === 200但是做了resp.json === 200而不是。