当使用Next Js Link时更新React类组件



原帖

我有一个React类组件,用于Next/JS动态路径。在初始加载时一切正常。但是有一个边缘用例,如果我在一个页面上,该组件已经挂载,然后点击一个Link,这是相同的动态基础作为组件路径,但有不同的参数,该组件不unmountgetIntialProps运行,但它不调用构造函数来更新新的状态。

例子:路径>

动态模式
/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更改为Router.push(),但结果相同。

问题:

  1. 是否有一种方法可以强制卸载一个组件,以允许创建一个新的实例。
  2. 如果不是以上,在组件生命周期中处理这种边缘情况的最佳方法是什么?我试图在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);
}
}

更新我将道具从状态中分离出来,以保持一个true源,并使用getDerivedStateFromProps()捕获更改并调用fetchPersonalData()。一切正常

唯一的问题是,它似乎需要两倍的时间来加载新的更新的道具/状态比初始加载。想法吗?

解决方案:对于我来说,这是由生命周期中的API调用引起的。

相关内容

  • 没有找到相关文章

最新更新