为了账号安全,请及时绑定邮箱和手机立即绑定

React componentDidUpdate 在 url 更改时不会更改

React componentDidUpdate 在 url 更改时不会更改

九州编程 2021-06-30 09:49:49
Match.params 没有在componentDidUpdate().我的路线是/sidebar/:id,如果从sidebar/1我去sidebar/2的this.props.match.params.id是仍然显示id为1,而不是更新的URLid 中2componentDidUpdate()尝试过props.location但仍然显示旧网址的数据。侧边栏页面组件 componentDidMount () {    const id  = this.props.match.params.id;    //fetching some data}componentDidUpdate(prevProps) {    console.log("Prevprops",prevProps.match.params.id);    console.log("Cuurent id",this.props.match.params.id);    //if both ids not same then fetch data again}路由器const routes = [  {    path: "sidebar/:id",    component: asyncComponent(() => import('../sidebarPage')),  },];class AppRouter extends Component {  render() {    const { url } = this.props; return (      <div>        {routes.map(singleRoute => {          const { path, exact, ...otherProps } = singleRoute;          return (            <Route              exact={exact === false ? false : true}              key={singleRoute.path}              path={`${url}/${singleRoute.path}`}           />          );        })}      </div>    );  }}我希望当我去sidebar/1到sidebar/2的componentDidUpdate this.props.match.params.id节目2和prevProps表演1。
查看完整描述

1 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

您asyncComponent仅使用初始值props并且不会对更改做出反应。


试试这个代码:


async componentDidMount() {

  this.mounted = true;

  const { default: Component } = await importComponent();

  Nprogress.done();

  if (this.mounted) {

    this.setState({

      component: Component

    });

  }

}


render() {

  const Component = this.state.component;

  return (

    <ReactPlaceholder type="text" rows={7} ready={Component !== null}>

      {Component ? <Component {...this.props}/> : <div/>}

    </ReactPlaceholder>

  );

}


查看完整回答
反对 回复 2021-07-01
  • 1 回答
  • 0 关注
  • 184 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信