首页 > 解决方案 > React Context Provider 不更新 Class.contextType

问题描述

我的应用程序使用 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 发生时组件没有重新渲染。我在主页的内容周围添加了消费者组件,但这并没有帮助。

我想出了一个将结果列表和方法列表也推送到上下文的想法,这样我就可以避免使用静态 contextType,但这对我来说似乎很骇人听闻。

关于我可能做错了什么的任何想法???

*****编辑***** 这是 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。

标签: javascriptreactjstypescriptreact-router

解决方案


经过大量研究,似乎处理此问题的正确方法是在 Context 对象中实际添加方法,以修改 App 中的状态(或任何包含 Context.Provider 对象的组件。


推荐阅读