我試圖從前端傳遞一個成績單(用戶通過對著麥克風說話),然后該資料將轉到后端,后端會將一個 JSON 物件回傳到前端。如何使我的網站在該程序(從前端到后端到前端的資料)發生時將用戶重定向到加載螢屏,然后最終一旦該程序完成,它將從該加載螢屏重定向它到將顯示該資料的“結果頁面”?
我正在使用反應版本6.14.13。有誰知道我能做些什么?
我的“主頁”中的這些功能將處理這個問題:
class Product extends Component {
constructor() {
super()
this.state = {
// Backend API data
data: {"data": {}}
}
}
handleSending() {
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
body: JSON.stringify(this.state.text)
};
fetch("http://127.0.0.1:5000/", options)
.then(response=> response.json())
.then(json => this.setState({data: json}))
.then(this.handleRedirect())
}
handleRedirect() {
// REDIRECT USER TO LOADING PAGE
// ONCE PROCESS IS DONE, REDIRECT USER TO "RESULTS PAGE"
}
}
uj5u.com熱心網友回復:
這是顯示加載頁面的常用方法。
并且要重定向“結果頁面”,我建議您使用像 React Router(https://reactrouter.com/)這樣的路由庫。
class Product extends Component {
constructor() {
super()
this.state = {
// Backend API data
data: {"data": {}},
loading: false
}
handleSending() {
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
body: JSON.stringify(this.state.text)
};
// Set loading true
this.setState({loading: true});
fetch("http://127.0.0.1:5000/", options)
.then(response=> response.json())
.then(json => this.setState({data: json}))
.then(this.handleRedirect())
.finally(()=> {
// Set loading false
this.setState({loading: false});
});
}
handleRedirect() {
// REDIRECT USER TO LOADING PAGE
// ONCE PROCESS IS DONE, REDIRECT USER TO "RESULTS PAGE"
// router.push("result_page");
}
render() {
return (
{this.state.loading && <div>loading...</div>
{!this.state.loading && <div>your product page</div>}
)
}
}
我想知道你為什么要使用這么舊的反應版本。
uj5u.com熱心網友回復:
首先從“react-router-dom”匯入 withRouter
import { withRouter } from "react-router-dom";
然后,您應該在默認匯出時使用 withRouter 包裝您的組件。
export default withRouter(Product);
然后您將可以訪問來自 props 的歷史記錄,您可以使用它的 push 方法將用戶推送到所需的頁面。
handleRedirect() {
this.props.history.push("/results-page");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/429446.html
