Match.params 未在 componentDidUpdate()
中更新。
我的路线是/sidebar/:id
如果来自sidebar/1
我去sidebar/2
this.props.match.params.id
仍然显示id
为 1 而不是更新后的 url id
2内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
显示1
.
最佳答案
您的asyncComponent
仅使用初始props
并且不会对更改使用react。
试试这个代码:
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>
);
}
关于javascript - React componentDidUpdate 不会在 url 更改时更改 props.match.params ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56594481/