需要手动刷新页面以更新它

时间:2019-11-12 13:52:49

标签: reactjs react-router

我为标头和内部创建了一个通用组件,有条件地渲染视图,但是每当路线更改时,我都必须手动刷新页面以查看更新的结果。

constructor(props) {
    super(props);
    this.state = {
      headerType: {
        home: ['/'],
        stepper: ['/decisionAid'],
      },
    };
  }

  render() {
    const { headerType } = this.state;
    let type = Object.keys(headerType).find(data =>
      headerType[data].includes(window.location.pathname),
    );
    return (
      <Router history={history}>
        <>
          <Header type={type} />
          <Switch>
            <>
              <Route path="/" exact component={HomePage} />
              <Route path="/decisionAid" component={Stepper} />
              <Route path="/notFound" component={NotFound} />
            </>
          </Switch>
        </>
      </Router>
    );
  }

当我更改页面时,由于URL的更改,标题应该自动更新,但我必须手动刷新它。

1 个答案:

答案 0 :(得分:0)

为了使标题能够访问您的URL,并重新渲染Header而又不重新渲染整个App对象,您可以将Header包裹在高阶成分withRouterhttps://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

这样做可以让您在道具中访问matchlocationhistory

import { withRouter } from "react-router-dom";

function Header(props) {
  const path = props.location.pathname.slice(1);

  return <h1>Hello {path}!</h1>;
}

const WrappedHeader = withRouter(Header);

这是一个有效的示例:https://codesandbox.io/s/react-boilerplate-8ucq4