重新渲染Reactjs组件

时间:2019-07-02 02:55:51

标签: reactjs react-router js-cookie

我有一个需要通过身份验证服务器(AS)和api调用进行身份验证的应用程序。 (AS)会将我需要设置一些浏览器cookie的信息重定向到我的应用程序,这将影响用户根据其权限级别看到的内容。

但是,我无法使我的应用程序检测到Cookie中的更改并进行相应渲染。我需要手动单击“刷新”按钮,以强制组件查看Cookie并提取信息。

我的问题是:当我从身份验证服务器重定向回我的react应用程序时,为什么没有调用render(),componentDidMount()之类的方法?

App.js:

componentDidMount() {
    console.log('App mounted!');
    const env = process.env.NODE_ENV;
    const code = this.getParameterByName('code');
    const stateID = this.getParameterByName('state');
    const authentication = new Authentication();
    const authorization = new Authorization();

    const sid = Cookies.get('sid'); 

    console.log('sid: ', sid);

    if (sid === undefined) {
      if (code === null || stateID === null) {
        authentication.signin(expressURL, env);
      } else {
        authentication.handleIDToken(expressURL, code, stateID).then(reply => {
          // console.log('Reply: ', reply);

          // let dt = new Date(reply.expiry * 1000).toUTCString();
          Cookies.set('userRole', reply.Role, {path: '/', expiry: new Date(reply.expiry * 1000).toUTCString()});
          Cookies.set('userName', reply.Name, {path: '/', expiry: new Date(reply.expiry * 1000).toUTCString()});
          Cookies.set('sid', reply.SID, {path: '/', expiry: new Date(reply.expiry * 1000).toUTCString()});
        });
      }
    }

    if (sid !== undefined && Cookies.get('apiToken') === undefined) {
      authorization.setDjangoApiToken(expressURL).then(response => {
        if (response === 200) {
          this.initialize();  // Populates my redux stores
        } else {
          this.setState({
            error: response
          });
        }
      });
    }
  }

还是我误解了一些React生命周期?

我正在使用React15和js-cookies

***我有一个Express.js后端,可以执行对身份验证服务器的这些调用。

欢呼

1 个答案:

答案 0 :(得分:0)

有两个选项:

  1. 强制您的应用重新加载window.location.reload();
  2. 向您的App.js中的componentDidUpdate()传递一些道具,并评估cookie是否已设置。
相关问题