【发布时间】:2019-06-14 08:39:12
【问题描述】:
Match.params 未在 componentDidUpdate() 中更新。
我的路线是/sidebar/:id,如果从sidebar/1 转到sidebar/2,this.props.match.params.id 仍将id 显示为1,而不是id 2 内componentDidUpdate() 中的更新网址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。
【问题讨论】:
-
您的示例代码有一些语法错误,似乎没有呈现
Sidebar。还添加一些关于asyncComponent的信息。它可能会阻止更新或将旧的props传递给真正的组件。
标签: javascript reactjs react-redux react-router