【发布时间】:2018-08-09 11:21:56
【问题描述】:
我的 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 上维护所有内容。 谢谢
【问题讨论】:
-
您通常希望坚持使用客户端路由或服务器端路由,而不是两者都使用
-
@BoyWithSilverWings 你是什么意思?
-
<Redirect to="/login" />在客户端路由,所以不会向后端发出请求 -
@BoyWithSilverWings 这是我要解决的问题,怎么能做到?我无法发帖表达
-
@BoyWithSilverWings 我也遵循了这个可以做我想做的事情的指南:github.com/ReactTraining/react-router/blob/master/packages/…
标签: javascript reactjs express react-router