reactjs - 使用 Next Js Link 时更新 React 类组件
问题描述
原帖
我有一个用于 Next/JS 动态路径的 React 类组件。在初始加载时一切都很好。但是有一个边缘用例,如果我在一个已经安装了该组件的页面上,然后单击与组件路径相同但具有不同参数的动态基础,Link
则该组件不会运行但它不会调用更新新状态的构造函数。unmount
getIntialProps
路径示例:
动态模式
/vos/[id]/[slug]
初始路径
/vos/203dk2-d33d-3e3e3d/thisName
新路径
/vos/554-34r4f-44d4e/aNewName
活动
1. component loads with initial props/state
2. user clicks Link to same component path but updated params
3. component lifecycles run to reset state but does not and does not unmount
4. 2-5 seconds pass... no activity
5. getIntialProps finally runs with new params
6. componentDidUpdate lifecycle called to update state with new props
我也尝试将其更改Link
为 aRouter.push()
但结果相同。
问题:
- 有没有办法强制卸载组件以允许创建它的新实例。
- 如果不在上面,那么在组件生命周期中处理这种边缘情况的最佳方法是什么?我尝试使用
componentDidUpdate()
循环中的函数更新状态,但这会有点混乱,因为它在SSR
调用之前运行,因此状态管理不同步。
代码示例
static getInitialProps = async (ctx: NextPageContext) => {
const services = VerifiedOrganizationProfilePage.PageServices(ctx);
const { lang: language, id: voId } = ctx.query as IProfilePagesQueryParams;
// check VO page is existing
// if VO owner or Admin
let verifiedOrganization: IVerifiedOrganizationResponse | undefined;
let user: IUserResponse | undefined;
let isVoOwner: boolean = false;
let isPlatformAdmin: boolean = false;
let isVoOwnerOrPlatformAdmin: boolean = false;
try {
verifiedOrganization = await services.verifiedOrganizationService.getVerifiedOrganization(voId);
if (!verifiedOrganization) throw new Error('No verified organization with that id was found!');
const userId = await services.cognitoIdentityService.getUserIdInSession();
if (userId) {
user = await services.usersService.getUser(userId);
isPlatformAdmin = AuthUtil.hasRoles(
[ERole.PLATFORM_ADMIN],
user.platformRoles
);
isVoOwner = OrganizationUtil.isVerifiedOrganizationOwner(
verifiedOrganization.id,
user
);
isVoOwnerOrPlatformAdmin = isVoOwner || isPlatformAdmin;
}
} catch (error) {
NextUtil.redirectTo(
'/not-found',
ctx.res,
HTTP_REDIRECT.TEMPORARY,
language
);
}
// fetch publicly visible data
const { store } = ctx;
store.dispatch(fetchCampaignsRequest({
verified_organization_id: voId,
limit: isVoOwnerOrPlatformAdmin ? EPaginationLimit.FIVE_HUNDRED : EPaginationLimit.DEFAULT,
}, ctx));
store.dispatch(fetchCausesRequest({
verified_organization_id: voId,
limit: EPaginationLimit.DEFAULT
}, ctx));
store.dispatch(fetchCommentsRequest({
verified_organization_id: voId,
limit: EPaginationLimit.DEFAULT
}, ctx));
store.dispatch(fetchUpdatesRequest({
verified_organization_id: voId,
limit: EPaginationLimit.DEFAULT
}, ctx));
// wait for redux saga updating state
await new Promise<void>((resolve) => {
const unsubscribe = store.subscribe(() => {
const state = store.getState();
if (!state.campaign.isFetching && !state.cause.isFetching && !state.comment.isFetching && !state.update.isFetching) {
unsubscribe();
resolve();
}
});
});
return {
user,
voId,
isVoOwner,
isPlatformAdmin,
verifiedOrganization,
isVoOwnerOrPlatformAdmin,
tabValue: EVerifiedOrganizationProfilePageTabs.CAMPAIGNS,
pageUrl: NextUtil.getPageUrl(ctx),
};
}
...
constructor(props){
super(props);
this.state = {...this.props}
}
...
// used to check new props from VO if coming from another VO page and set the state
static async getDerivedStateFromProps(nextProps: IVerifiedOrganizationProfilePageProps, prevState: IVerifiedOrganizationProfilePageState) {
if (nextProps.voId !== prevState.voId) {
return {
voId: nextProps.voId,
urlChanged: true,
tabValue: EVerifiedOrganizationProfilePageTabs.CAMPAIGNS,
isWaitingAdminApproval: false,
isUserBothVoAndIpRepresentative: false,
visibleBeneficiaryList: listResponse,
beneficiaryGroups: listResponse,
followingVerifiedOrganizations: {},
beneficiaryBlockchainCSVData: undefined,
userRating: undefined,
isLoading: true,
};
}
}
...
async componentDidMount() {
Router.events.on('routeChangeStart', this.handleRouteChangeComplete); // to trigger callback beofre NEXT Router/Link executes
await this.fetchPersonalData(); // method to fetch user specific data
}
...
async componentDidUpdate() {
if (this.state.urlChanged) {
await this.fetchPersonalData();
}
}
...
componentWillUnmount() {
Router.events.off('routeChangeStart', this.handleRouteChangeComplete);
}
...
// sets the current open tab to CAMPAIGNS if a VO navigates to a connected VO profile from a restricted tab
public handleRouteChangeComplete = async (url: string) => {
this.setState({tabValue: EVerifiedOrganizationProfilePageTabs.CAMPAIGNS,});
}
...
public fetchPersonalData = async () => {
const { voId, user, verifiedOrganization, isPlatformAdmin, isVoOwnerOrPlatformAdmin } = this.props;
let isVoRepresentative: boolean = false;
let isIpRepresentative: boolean = false;
let isUserBothVoAndIpRepresentative: boolean = false;
let isWaitingAdminApproval: boolean = false;
let visibleBeneficiaryList: IListResponse<IBeneficiaryWithInvitationStatus> | undefined;
let beneficiaryGroups: IListResponse<IGroup> | undefined;
try {
const services = VerifiedOrganizationProfilePage.PageServices();
if (user) {
isWaitingAdminApproval = verifiedOrganization.verifiedOrganizationStatus === EVerifiedOrganizationStatus.PENDING_PLATFORM_ADMIN_APPROVAL;
// If Verified Organization is waiting for Admin Platform approval, only Platform Admin can see the page.
if (isWaitingAdminApproval && !isPlatformAdmin) {
throw new NotFoundError();
}
isVoRepresentative = AuthUtil.hasRoles(
[ERole.VERIFIED_ORGANIZATION_REPRESENTATIVE],
user.platformRoles
);
isIpRepresentative = AuthUtil.hasRoles(
[ERole.IMPLEMENTING_PARTNER_REPRESENTATIVE],
user.platformRoles
);
isUserBothVoAndIpRepresentative =
isVoRepresentative && isIpRepresentative;
// If Verified Organization is waiting for Admin Platform approval, only Platform Admin can see the page.
if (isWaitingAdminApproval && !isPlatformAdmin) {
throw new NotFoundError();
}
// add the prefix to the id so we can match the record in the Connections table.
const prefixedId = EIdTypes.VERIFIED_ORGANIZATION.toUpperCase() + '#' + verifiedOrganization.id;
// Fetch data visible only to VoOwner and Aidonic
const connections = [] as unknown as IListResponse<IConnectionVOIP>;
if (isVoOwnerOrPlatformAdmin) {
// Get from the API all the connections sent or received
// Commenting this out as it calling twice the API. The call to the API is done from the Tab instead.
// connections = await services.connectionsService.getVisibleConnectionsByOrganization(prefixedId);
visibleBeneficiaryList = await services.beneficiaryService.getBeneficiariesVisibleToOrganization(prefixedId);
beneficiaryGroups = await services.beneficiaryGroupsService.getBeneficiaryGroupsList(prefixedId, {limit: EPaginationLimit.THIRTY});
}
const follows = await services.followsService.getFollowsList({
user_id: user.id
});
const [followingVerifiedOrganizations] = mapFollowsByKey(follows, [
'verifiedOrganizationId'
]);
const userRating = await services.ratingsService.getRatingList({
user_id: user.id,
verified_organization_id: verifiedOrganization.id
});
this.setState({
voId,
connections,
tabValue: EVerifiedOrganizationProfilePageTabs.CAMPAIGNS,
beneficiaryGroups,
isWaitingAdminApproval,
visibleBeneficiaryList,
followingVerifiedOrganizations,
isUserBothVoAndIpRepresentative,
userRating: userRating && userRating[0],
isLoading: false,
urlChanged: false
});
}
} catch (e) {
console.log('Error in data fetching on VO profile page: ', e);
}
}
更新
我已经将 props 从 state 中分离出来,以保持一个 true 来源,并用于getDerivedStateFromProps()
捕捉 change 和 call fetchPersonalData()
。一切运作良好。
唯一的问题是加载新更新的道具/状态所需的时间似乎是初始加载的两倍。想法?
解决方案
解决方案:就我而言,这是由生命周期中的 API 调用引起的。框架运行良好。
推荐阅读
- blazor - Blazor WASM 文件不存在(但可读吗?)
- sdn - 如何在 POX 控制器中添加流规则
- excel - Power Query 源项目不区分大小写
- algorithm - 遍历 2 个地图,在同一行输出上保留顺序
- python - 从接近熊猫中另一个值的列列表中选择值
- python - 在 Python 中删除循环中的 JSON 元素
- vue.js - 导入非 vue 包(如 Flickity)时 Nuxt.js 中出现“未定义窗口”错误 - 尽管使用客户端模式并检查 process.client
- exception - .Net Core Web API 处理不同层的异常
- go - 附加/添加到具有两个值的地图
- javascript - 脚本标签不会一直加载