Reactjs 需要手动刷新页面才能进行更新

Reactjs 需要手动刷新页面才能进行更新,reactjs,react-router,Reactjs,React Router,我已经为header和inside创建了一个公共组件,我正在有条件地呈现视图,但是每当路由更改时,我都必须手动刷新页面以查看更新的结果 constructor(props) { super(props); this.state = { headerType: { home: ['/'], stepper: ['/decisionAid'], }, }; } render() { const { he

我已经为header和inside创建了一个公共组件,我正在有条件地呈现视图,但是每当路由更改时,我都必须手动刷新页面以查看更新的结果

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>
    );
  }
构造函数(道具){
超级(道具);
此.state={
标题类型:{
首页:['/'],
步进器:['/decisionAid'],
},
};
}
render(){
const{headerType}=this.state;
let type=Object.keys(headerType).find(数据=>
headerType[data].includes(window.location.pathname),
);
返回(
);
}

当我更改页面时,由于url的更改,页眉应自动更新,但我必须手动刷新它。

为了使页眉能够访问您的url,并使
页眉重新呈现,而无需重新呈现整个
应用程序
对象,您可以使用路由器将
标题
环绕高阶组件

这样做可以让您在道具中访问
匹配
位置
、以及
历史

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);
从“react router dom”导入{withRouter};
功能标题(道具){
const path=props.location.pathname.slice(1);
返回Hello{path}!;
}
const WrappedHeader=带路由器(标头);

下面是一个工作示例:

在页面加载时,
Header
所在的组件只呈现一次。仅更改管线不会导致其重新渲染。如果您想要这种行为,您需要保留一个本地状态。您好@Kyle谢谢您的回答,但我没有完全理解该部分,我是否需要在需要的每个组件中分别导入标题,请详细说明您的答案。非常感谢@Kyle,它完全按照我的要求工作