反应componentDidUpdate不改变URL更改props.match.params?

时间:2019-06-14 08:39:12

标签: javascript reactjs react-redux react-router

Match.params在componentDidUpdate()中未得到更新。

如果从/sidebar/:idsidebar/1,我的路线是sidebar/2,而this.props.match.params.id仍将id显示为1,而不是更新的URL {{ 1}} 2个位于id

尝试过componentDidUpdate(),但仍显示旧网址的数据。

侧边栏页面组件

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>
    );
  }
}

我希望当我从import React, { Component } from 'react'; import Nprogress from 'nprogress'; import ReactPlaceholder from 'react-placeholder'; import 'nprogress/nprogress.css'; import 'react-placeholder/lib/reactPlaceholder.css'; export default function asyncComponent(importComponent) { class AsyncFunc extends Component { constructor(props) { super(props); this.state = { component: null }; } componentWillMount() { Nprogress.start(); } componentWillUnmount() { this.mounted = false; } async componentDidMount() { this.mounted = true; const { default: Component } = await importComponent(); Nprogress.done(); if (this.mounted) { this.setState({ component: <Component {...this.props} /> }); } } render() { const Component = this.state.component || <div />; return ( <ReactPlaceholder type="text" rows={7} ready={Component !== null}> {Component} </ReactPlaceholder> ); } } return AsyncFunc; } 中的sidebar/1sidebar/2时,componentDidUpdate显示this.props.match.params.id,而2显示prevProps

1 个答案:

答案 0 :(得分:2)

您的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>
  );
}