React Router在没有支持的组件的路线更改时获取数据

时间:2018-08-13 03:09:38

标签: reactjs react-router react-router-dom

在Switch路由器场景中,在返回到已经安装的没有任何道具的组件之后,我们如何从服务器获取新数据。在问这个之前,我浏览了很多帖子。所有帖子均建议使用componentWillRecieveUpdate。如果组件没有任何道具,则永远不会调用此生命周期挂钩。我什至尝试过getDerivedStatefromProps

处理这种情况的最佳选择是什么??

import React from "react";
import { render } from "react-dom";

// import react router
import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom";

class Application extends React.Component {
  render() {
    return (
      <Router>
        <div>
          <Menu />
          <div>
            <Switch>
              <Route path="/help" component={Help} />
              <Route exact path="/" component={OverView} />
              <Route component={OverView} />
            </Switch>
          </div>
        </div>
      </Router>
    );
  }
}

class Menu extends React.Component {
  render() {
    return (
      <ul>
        <li>
          <Link to="/help">Help</Link>
        </li>
        <li>
          <Link to="/">OverView</Link>
        </li>
      </ul>
    );
  }
}

class Help extends React.Component {
  render() {
    return (
      <div>
        <p>Some help</p>
      </div>
    );
  }
}

class OverView extends React.Component {
  constructor(props, context) {
    super(props);
    this.state = {};
  }

 getDerivedStatefromProps(prevprops,prevstate, ){
   //Even this will also not be called
 }

 componentWillRecieveUpdate(newprops)
 {
     //I dont recieve a call to this when come back from help
 }

  render() {
    //can we fetch data here and save in the state
    // and re-render. Will this cause any issues
    return <div> How to return fetch data</div>;
  }
}

render(<Application />, document.getElementById("root"));

1 个答案:

答案 0 :(得分:0)

我一直在研究您的代码,请注意,您的组件每次都在安装,而不是您声称的那样一次安装。

请阅读React Router doc了解更多信息。

您可以在Demo

中看到它
class OverView extends React.Component{
  constructor(props,context) {
    super(props)
    this.state = {}
  }

  componentDidMount() {
    console.log('mounted');
  }

  render() {
    console.log('render');
    return(<div> How to return fetch data</div>)
  }
}