javascript - React-router 如何重定向到 Express GET

标签 javascript reactjs express react-router

我正在为我的网络应用同时使用 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/

相关文章:

javascript - 如何为我的 WebSocket 实现 channel 逻辑,包括可以绑定(bind)的事件?

javascript - Angular 保持对象通过应用程序同步

javascript - 仅在一个组件中调用方法

javascript - 没有包装 div 的 ReactMarkdown

jquery - 在 jasmine 测试中使用 React 组件触发 jQuery 事件,无需开玩笑

javascript - Node.js 将变量显示为 HTML

javascript - node js中的面向对象编程

javascript - 检测操作系统(XP 与 7)

javascript - 计算像 "loop "这样的数字

javascript - 路由内的 Express.js http 调用不更新变量