Match.params在componentDidUpdate()
中未得到更新。
如果从/sidebar/:id
到sidebar/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/1
到sidebar/2
时,componentDidUpdate
显示this.props.match.params.id
,而2
显示prevProps
。
答案 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>
);
}