简体   繁体   English

ReactJS组件会在历史记录转发时重新加载吗?

[英]Does ReactJS Component reload on History Forward?

I ran into an interesting issue setting up routes in my app. 我在应用程序中设置路由时遇到了一个有趣的问题。 I have a component that requests an html stream from the server when the component is loaded based on a props.doctype variable: 我有一个组件,当根据props.doctype变量加载组件时,它会从服务器请求html流:

import {ajaxCall} from '../global';
import React,{Component} from "react";
import Panel from '../comp/panel/panel';

import "./login.css";

    class Legal extends Component{
      constructor(props,context){
        super(props,context);
        this.state = {data: ""}
      };
      componentDidMount(){
        let opts = {"type":this.props.doctype};
        ajaxCall("http://localhost:5000/legal",opts,this.handleResponse.bind(this))
      };
      handleResponse(resp){
        console.log(this.state)
        let data = resp.data;
        this.setState({data:data});
      };
      render(){
        return(
          <div className="legal" dangerouslySetInnerHTML={{__html: this.state.data}}></div>
      )};
    }
    export default Legal

The Route to this component looks like this: 到该组件的路由如下所示:

<Route path="/Login/Terms" render={(props)=><Legal doctype="terms"/>} />

and the Link: 和链接:

<NavLink to={pathname:"/Login/Terms",doctype:"terms"}}>Terms</NavLink>

The problem I am running into is when the Legal component loads, it correctly loads the associated html from the server; 我遇到的问题是,当Legal组件加载时,它正确地从服务器加载了相关的html。 however, if I hit the back button on the browser and then the forward button, I get a blank page with no errors. 但是,如果我按浏览器上的“后退”按钮,然后按“前进”按钮,则会得到一个空白页面,没有错误。 Is there an issue with the way I am routing? 我的路由方式是否存在问题?

*Edit * Login Component: *编辑*登录组件:

import React from "react";
import {BrowserRouter as Router, Route} from "react-router-dom"
import LoginForm from "./loginform";
import Legal from "./legal";

const Login = (props) =>{
  return(
    <Router>
        <div className="content">
          <Route exact path="/Login" component={LoginForm} />
          <Route path="/Login/Terms" render={(props)=><Legal doctype="terms"/>} />
          <Route path="/Login/Privacy" component={Legal} />
          <Route path="/Login/Recoverpw" component={Recover} />
        </div>
    </Router>
  );
};
export default Login;

I think the problem is here: 我认为问题出在这里:

<NavLink to={pathname:"/Login/Terms",doctype:"terms"}}>Terms</NavLink>

When you are routing like this you have doctype props in the Legal component but when you direclty load the component from url like http://localhost:3000/Login/Terms , the component no longer has the doctype prop, so it can't fetch the HTML content appropriately and renders a white screen. 像这样进行路由时,在Legal组件中有doctype属性,但是当您直接从url中加载该组件时,例如http://localhost:3000/Login/Terms ,该组件就不再具有doctype属性,因此无法适当地获取HTML内容并呈现白屏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM