0
我在前端有React.js,後端有Express.js。此刻,我試圖從刪除請求中刪除React的帖子,並且它可以正常工作,但我必須轉到url並在刪除之後顯示新列表之前按回車鍵。我希望頁面不必刷新即可重新渲染。發送刪除請求後,重新呈現反應不起作用
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();
}
})
}
}
功能handleDeleteButton
應取所有房源,並使其無需刷新,因爲它調用fetchAllRentals
功能,但它不工作的某些原因。
我想知道你的'this.setState'實際上是否工作,因爲'this'的值我不是你所期望的。嘗試將其設置爲函數頂部的變量。例如'fetchAllRentals(){var that = this'那麼你可以使用'that.setState' ... –
當你調用DELETE API時,你可以檢查你的'resp.json'是什麼嗎? – palsrealm
你好,發現出了什麼問題,想做'resp.status === 200'看看它是否會通過然後取回。出於某種原因,我正在做resp.json。謝謝 – craftdeer