首页 > 解决方案 > React Context API 和子组件刷新

问题描述

我有一个 Context 组件,当我设置某个值时,我希望它们影响使用它的其他组件,但我的理解在这里似乎是错误的。

我有一个主要处理屏幕布局的 MainComponent 组件。

import { Consumer } from './context';

class MainContainer extends React.Component {


    render() {

        const noPadding = {
            margin: 0,
            padding: 0
          }

        const isAuthenticated = this.context.isAuthenticated()  

        return (
            <HashRouter>
            <Header />
            <Container>
              {isAuthenticated && 
              <AuthorisedArea>
                <Row style={noPadding}>
                  <Col md="3"  style={noPadding}>
                    <RightInfoBar />
                  </Col>
                  <Col md="9">
                      <RouteManager />
                  </Col>
                </Row>
              </AuthorisedArea>
              }
            </Container>
          </HashRouter>
        )
    }
}

MainContainer.contextType = Consumer;
export default MainContainer

当用户登录时,这一切都应该起作用。当他们注销时,现在,我真的希望看到一个空白屏幕。

在我的导航栏中,当用户单击注销时,我会这样做:

 handleLogout() {
      const { toastManager } = this.props;
      const { pathname } = this.props.location;
      this.context.changeAuthenticated(false);
      this.context.logout();

      if(pathname !== "/") {
        this.props.history.push("/");
      }
      toastManager.add('You\'re now logged out', {
        appearance: 'success',
        autoDismiss: true,
        pauseOnHover: false,
      });
    }

更新我的上下文组件中的this.context.logout属性,将“isAuthenticated”设置为 false。

所以我的基本上下文组件:

const Context = React.createContext();

export class Provider extends React.Component {

    state = {
        user: {
            name: "",
            email: "",
            authStatus : Auth.isAuthenticated()
        },
        changeEmail: (newEmail) => {
            let user = this.state.user;
            user.email = newEmail;
            this.setState({ user: user})
        },
        changeAuthenticated: (newState) => {
            if(newState ===false) Auth.logout();
            let user = this.state.user;
            user.name = "Craig";
            this.setState ({ user: user });
        },
        logout: () => {
            console.log("Will logout");
            Auth.logout();
            this.setState({authStatus: false});
        },
        isAuthenticated: () => {
            return Auth.isAuthenticated()
        }
    }

    render() {
        return (
            <Context.Provider value={this.state}>
                {this.props.children}
            </Context.Provider>
        )
    }
}

export const Consumer = Context.Consumer;

所以,我希望我的主要组件会注意到 isAuthenticated 变为假......并且屏幕会变成空白(现在......一旦我有这个工作,我会做更好的事情)。

但是当我单击注销时 - 控制台指示 Context 组件中的方法被触发......并且值变为假......但屏幕仍然存在。

只有当我按 F5 时,屏幕才会按预期运行。

我应该如何MainComponent对 React.Context 值更改做出反应?

标签: javascriptreactjsreact-context

解决方案


推荐阅读