繁体   English   中英

反应上下文提供者不更新Class.contextType

[英]React Context Provider not updating 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发生时为什么不重新渲染组件。 我在首页内容周围添加了Consumer Component,但这没有帮助。

我想到了将结果列表和方法列表也推到Context的想法,这样我就可以避免使用静态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。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM