[英]React-router how to redirect to an Express GET
我的 web 應用程序同時使用 Express 和 React,因為我們正在將渲染從 Handlebars 遷移到 React。 然而,我們希望在 Express 中維護邏輯並僅在 React 中呈現。 問題是當我想做重定向時。 這是帶有邏輯的 client.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import { BrowserRouter } from "react-router-dom";
// In production, we want to hydrate instead of render
// because of the server-rendering
if (process.env.NODE_ENV === 'production') {
ReactDOM.hydrate(
<BrowserRouter>
<App {...window.__APP_INITIAL_STATE__} />
</BrowserRouter>
, document.getElementById('app'));
} else {
ReactDOM.render(
<BrowserRouter>
<App {...window.__APP_INITIAL_STATE__} />
</BrowserRouter>
, document.getElementById('app'));
}
// Hot reload is that easy with Parcel
if (module.hot) {
module.hot.accept();
}
這是 Express 的簡單路徑:
app.get('/signup', (req,res)=>{
const initialState = {component:'SignUp'};
let context = {};
const markup = ReactDOM.renderToString(
<StaticRouter location={req.url} context={context}>
<App {...initialState} />
</StaticRouter>
);
if (context.url) {
res.writeHead(302, {
Location: context.url
});
res.end();
}
else {
res.send(generateHtml(markup,initialState));
}
});
問題是:當我嘗試像這樣重定向(並更改 this.state.redirect)時:
render(){
return this.state.redirect ? <Redirect to="/login" /> :(
<div className="ro">HI </div> );
}
瀏覽器轉到 /login 路徑,但不調用服務器。 它簡單地顯示一個空白頁面。
這也是我的 App 組件:
export default class App extends Component {
constructor(props){
super(props);
console.log(props);
}
render(){
if(this.props.component === 'Root'){
return <Root />;
}
else if(this.props.component === 'Login'){
return <Login />;
}
else if(this.props.component === 'SignUp'){
return <SignUp />;
}
else{
return (
<div>
<h1>Hello word {this.props.component}</h1>
<Button color="danger">Danger!</Button>
</div>
);
}
}
}
那是一個管理去哪里的根組件。
如何解決這個問題? 我不想使用 react-router 來處理路由,我們想在 Express 上維護所有內容。 謝謝
在客戶端渲染時,您可以window.location.replace("/login");
而不是設置狀態來渲染<Redirect>
window.location.replace("/login");
模擬<Redirect push>
: window.location.href = "/login";
在服務器端,您可以繼續使用<Redirect>
您可以在子域上托管您的 Express 應用程序:
<Redirect to="http://express.myapp.com/login" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.