使用上下文进行条件渲染失败

时间:2019-03-31 20:13:53

标签: reactjs react-context react-material

以下是在侧面导航中正确更改“登录”和“注销”的组件,但在正常情况下不起作用。基本上,即使登录成功,“ LoginLogOutButton”组件也不会重新呈现。另一个auth.js文件中编写的“ isAuthenticated”函数,该文件根据登录/注销返回true或false。

AuthContext

import React from "react";
const AuthContext = new React.createContext();
export default AuthContext;

AuthContext.Provider

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      auth: new Auth(this.props.history),
      tokenRenewalComplete: false,
      classes: this.props.classes
    };
  }

  componentDidMount() {
    this.state.auth.renewToken(() =>
      this.setState({ tokenRenewalComplete: true })
    );
  }

  render() {
    const { classes, auth } = this.state;
    // Show loading message until the token renewal check is completed.
    if (!this.state.tokenRenewalComplete) return "Loading...";
    return (
      <AuthContext.Provider value={auth}>
        <NavBar />
        <div className={classNames(classes.main)}>
          <div className={classes.container}>
            <Switch>
              <Route path="/blog/detail" component={BlogDetail} />
              <Route path="/blog" component={Blog} />
              <Route path="/courses" component={CoursesPage} />
              <Route path="/course/:slug" component={ManageCoursePage} />
              <Route path="/course/" component={ManageCoursePage} />
              <Route
                path="/callback"
                render={props => <Callback auth={auth} {...props} />}
              />
              <Route path="/public" component={Public} />
              <PrivateRoute path="/private" component={Private} />
              <Route path="/" component={Home} />
            </Switch>
            <ToastContainer autoClose={3000} hideProgressBar />
            <Footer />
          </div>
        </div>
      </AuthContext.Provider>
    );
  }
}

export default withStyles(landingPageStyle)(App);
  

注意:HeaderLinks是NavBar的子组件

AuthContext.Consumer

   import AuthContext from "../../../AuthContext";
    const LoginLogOutButton = props => {
      if (props.auth.isAuthenticated())
        return (
          <ListItem className={props.classes.listItem}>
            <Link
              to="/"
              className={props.classes.navLink}
              onClick={props.auth.logout}
            >
              <Person className={props.classes.icons} />
              Log Out
            </Link>
          </ListItem>
        );
      else
        return (
          <ListItem className={props.classes.listItem}>
            <Link
              to="/"
              className={props.classes.navLink}
              onClick={props.auth.login}
            >
              <Person className={props.classes.icons} />
              Log In
            </Link>
          </ListItem>
        );
    };

    class HeaderLinks extends Component {
      constructor(props) {
        super(props);
      }
      render() {
        const { classes } = this.props;
        return (
          <AuthContext.Consumer>
            {auth => (
              <List >
                <ListItem>
                  <CustomDropdown
                    noLiPadding
                    buttonText="Menu"
                    buttonProps={{
                      className: classes.navLink,
                      color: "transparent"
                    }}
                    buttonIcon={Apps}
                    dropdownList={[
                      <Link to="/">
                        Home
                      </Link>,
                      <Link to="/blog" >
                        Blog
                      </Link>
                    ]}
                  />
                </ListItem>

                <LoginLogOutButton auth={auth} {...this.props} />

              </List>
            )}
          </AuthContext.Consumer>
        );
      }
    }

    export default withStyles(headerLinksStyle)(HeaderLinks);`enter code here`

enter image description here 感谢您的帮助

1 个答案:

答案 0 :(得分:0)

很难说没有看到您的AuthContext,但是我很确定问题是您将auth对象作为不变的道具传递,即,相同的对象/相同prop,因此React不会触发更新。相反,您应该直接传递isAuthenticated值,请注意,我的意思不是函数,而是布尔值(truefalse)。在这种情况下,您的组件将正确更新。