【发布时间】:2019-04-12 20:05:51
【问题描述】:
我的应用使用 React Context Provider 来传递用户配置文件。在我的 App 组件中,我的状态定义为:
interface IState {
authUser: any;
userProfile: IProfile;
roles: string[];
}
在我的 componentDidMount 方法中,我使用 fetch 调用三个不同的 API。然后结果为相应的条目调用 setState。 我的应用程序的渲染部分是:
<AuthenticationContext.Provider value={this.state}>
<BrowserRouter>
<div>
<Navigation />
<Switch>
/* Other routes removed for brevity */
<Route exact={true} path={routes.HOME} component={Home} />
</Switch>
<Footer />
</div>
</BrowserRouter>
</AuthenticationContext.Provider>
在 Home 组件中,我使用的是静态 Class.contextType 条目:
public static contextType = AuthenticationContext;
public context!: React.ContextType<typeof AuthenticationContext>;
然后在 componentDidMount 方法中,我使用 this.context.userProfile 对象中的条目调用另一个 API。
我添加了控制台日志语句来跟踪整个生命周期。当我重新加载页面时,我得到了这个:
Calling /api/profiles/getAdminStatus/7J4OwwnmQ1fMhavSLeLkDkKe9Kl2
Calling getProfile within App
Calling /api/profiles/7J4OwwnmQ1fMhavSLeLkDkKe9Kl2 within getProfile
Calling /api/profiles/7J4OwwnmQ1fMhavSLeLkDkKe9Kl2 within getLookingFor
Calling loadProfiles
Calling getFilterResults with Userid:
Calling /api/search
About to setState in getProfile within App: UserId: 7J4OwwnmQ1fMhavSLeLkDkKe9Kl2
getFilterResults 显示一个空白的 Userid 条目。但是,如果我浏览到另一个页面,然后返回此页面,我会得到以下结果:
Calling /api/profiles/7J4OwwnmQ1fMhavSLeLkDkKe9Kl2 within getLookingFor
Calling loadProfiles
Calling getFilterResults with Userid: 7J4OwwnmQ1fMhavSLeLkDkKe9Kl2
Calling /api/search
根据这些消息,我确定问题是在 Home 组件加载之前获取当前用户的初始调用没有返回。但是,我不明白为什么当 setState 发生时组件没有重新渲染。 我在主页的内容周围添加了消费者组件,但这没有帮助。
我想出了一个将结果列表和方法也推送到 Context 的想法,这样我就可以避免使用静态 contextType,但这对我来说似乎是 hackish。
对我可能做错了什么有什么想法???
*****编辑***** 这是 Home 组件:
interface IHomeComponentState {
profiles: IProfileShort[];
hasMore: boolean;
error: boolean;
isLoading: boolean;
}
class HomeComponent extends React.Component<any, IHomeComponentState> {
public static contextType = AuthenticationContext;
public _isMounted = false;
public context!: React.ContextType<typeof AuthenticationContext>;
private currentPage: number = 0;
constructor(props: any) {
super(props);
this.state = {
profiles: [],
hasMore: true,
error: false,
isLoading: false,
};
this.loadProfiles.bind(this);
window.onscroll = () => {
if (this.state.error || this.state.isLoading || !this.state.hasMore) {
return;
}
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
this.loadProfiles();
}
};
}
public loadProfiles() {
if (this.context) {
const value = this.context;
// tslint:disable-next-line: no-console
console.log(
'Calling getFilterResults with Userid: ' + value.userProfile.userId,
);
getFilterResults(
value.userProfile.gender,
value.userProfile.lookingForGender,
value.userProfile.minAge,
value.userProfile.maxAge,
value.userProfile.connectionType,
value.userProfile.dateOfBirth,
this.currentPage,
)
.then(newProfiles => {
this.setState(
{
profiles: [...this.state.profiles, ...newProfiles],
},
() => {
this.currentPage = this.currentPage + 1;
},
);
})
.catch();
}
}
public componentDidMount() {
// tslint:disable-next-line: no-console
console.log('Calling loadProfiles');
this.loadProfiles();
}
public render() {
return (
<Grid container justify="center" direction="column" alignContent="center">
<Paper>
<Grid container item spacing={40} style={{ maxWidth: '840px' }}>
{this.state.profiles.map(profile => (
<Grid
key={profile.userId}
item
sm={6}
style={{ maxWidth: '200px' }}
>
<Link
to={`/profile/${profile.userId}`}
style={{ textDecoration: 'none' }}
>
<ProfileCard
key={profile.userId}
name={profile.name}
picUrl={profile.picUrl}
userId={profile.userId}
age={profile.age}
orientation="horizontal"
location={profile.location}
/>
</Link>
</Grid>
))}
</Grid>
</Paper>
</Grid>
);
}
}
const authCondition = (authUser: any) => !!authUser;
export const Home = withAuthorization(authCondition)(HomeComponent);
另外,我的 react 和 react-dom 版本都是 16.8.6。
【问题讨论】:
-
一切都发生在您的 Home 组件中?如果可以,您可以发布该组件吗?
标签: javascript reactjs typescript react-router