在反应中保护路线?

Securing routes in react?

class SecuredRoute extends Component {
  constructor(props) {
    super(props);
    this.state = {
      reputationNumber: 0,
    }

    this.getReputationNumber = this.getReputationNumber.bind(this);
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  componentWillMount() {
    this._isMounted = true;
    this.getReputationNumber();
  }

  getReputationNumber() {
    axios.get(`http://localhost:3000/api/userDatas/${getUserDataId()}`)
      .then(response => {
        const reputationNumber = response.data.reputationNumber;
        this._isMounted && this.setState({ reputationNumber });
      }).catch(err => console.log(err));
  }

  render() {
    const { component: Component, path } = this.props;
    const { reputationNumber } = this.state;
    return (
      <Route path={path} render={() => {
        console.log("reputationNumber: ", reputationNumber);
        if (isUserAuthenticated() && reputationNumber >= 500) {
          return <Component />
        }
        else {
          this.props.history.push('/login');
          return <div></div>
        }

      }} />
    );
  }
}


<SecuredRoute exact path='/tag/add' component={AddTag} />

我只是在做一个类似 SO 的问答网络应用程序。我正在尝试保护我的路线,/tag/add,用户有信誉号,此组件检查用户是否经过身份验证并且信誉号 >= 500 如果是,它 returns 组件重定向到登录.但问题是在第一次渲染时我不知道用户的信誉号码,它来自服务器所以在这段时间之间用户总是重定向到'/ login'但我希望用户访问 /tag/add 组件,如果他已通过身份验证并具有 >= 500 的信誉号。

感谢任何帮助。

我一直在处理我预期采取行动但尚未收到的数据的显示方式,它会显示一个加载指示器,直到返回所需的数据。

添加一个标记来跟踪您是否已收到初始响应可以在组件状态中完成:

  constructor(props) {
        super(props);
        this.state = {
            reputationNumber: 0,
            loaded = false, //Add to init state
        }
        
        this.getReputationNumber = this.getReputationNumber.bind(this);
    }
    
  getReputationNumber() {
        axios.get(`http://localhost:3000/api/userDatas/${getUserDataId()}`)
            .then(response => {
                const reputationNumber = response.data.reputationNumber;
                this._isMounted && this.setState({ reputationNumber, loaded: true });
            }).catch(err => console.log(err));
    }

希望对您有所帮助!