我正在为我的网络应用同时使用 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>
);
}
}
}
这是一个 Root 组件,负责管理去向。
如何解决这个问题?我不想使用 react-router 来处理路由,我们想在 Express 上维护所有。 谢谢
最佳答案
客户端渲染时,不是设置状态渲染一个<Redirect>
, 你可以 window.location.replace("/login");
模拟<Redirect push>
: window.location.href = "/login";
在服务器端,你可以继续使用<Redirect>
关于javascript - React-router 如何重定向到 Express GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49048884/