【问题标题】:Having problems with React Router Auth redirectionReact Router Auth 重定向有问题
【发布时间】:2019-08-04 01:39:26
【问题描述】:

我正在尝试使用此处显示的反应路由器身份验证重定向 (https://reacttraining.com/react-router/web/example/auth-workflow),但我遇到了很多问题。我目前收到一个错误:无法读取未定义的属性“状态”。我无法弄清楚我做错了什么。任何帮助将不胜感激。另外,我很想听听您对我的代码的任何注释/改进(这是我使用 React 的时间)。

错误来自 Login 类渲染函数中的 {from} 这是codeandbox的链接,它有更完整的代码:https://codesandbox.io/embed/bold-mendel-hgvun

`const auth = {
isAuthenticated: false,
authenticate(callback) {
  this.isAuthenticated = true;
  setTimeout(callback, 30000);
},
signout(callback) {
  this.isAuthenticated = false;
  setTimeout(callback, 30000);
}
};

 //Class Login:
 handleSubmit(event){
  event.preventDefault();
  var payload = {
    "email": this.state.email,
    "password": this.state.password
  }
  axios.post({url}"/login", payload)
  .then((res) => {
    console.log(res);
    if (res.data.status == "success") {
      auth.authenticate(() => {
        this.setState({ redirectToReferrer: true});
      });
      this.setState({authenticated: true});
      this.setState({token: res.data.data.token})
    }
}


render() {
  let {from} = this.props.location.state || {from: {pathname: '/'}};
  const { redirectToReferrer } = this.state;
  if (redirectToReferrer == true) {
    return <Redirect to={from} />
  }
  return (
          <form>
            <input value={this.state.email} onChange={this.handleChange} type="email" name="email" placeholder="Email" />
            <input value={this.state.password} onChange={this.handleChange} type="password" name="password" placeholder="Password" />
            <button type="submit" onClick={this.handleSubmit} className="btn btn-primary">Login</button>
          </form>
  );
}
  }

 const PrivateRoute = ({ component: Component, authed, ...rest }) => (
<Route {...rest} render={(props) => (
  authed === true
    ? <Component {...props} />
    : <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }} />
)} />
  );

//called in class App like this 
render() {
const {authenticated}=this.state;
return(
  <React.Fragment className='root'>
    <Router>
      <Switch>
          <Route path="/login" render={() => <Login callbackToParent={this.loginCallback} /> }exact/>
          <Route path="/register" render={() => <Register callbackFromParent={this.registerCallback} /> } exact/>
  <PrivateRoute authed={authenticated} path="/" render={() => <Home tokenFromParent={this.state.token} /> } exact/>
      </Switch>
    </Router>
  </React.Fragment>

  );`

【问题讨论】:

  • handleSubmit 函数有效吗??我不觉得网址不对??
  • 函数表达式 PrivateRoute 声明在哪里? (哪个文件)
  • 您的路由器配置正确了吗?状态未定义可能是因为组件没有从反应路由器接收到道具“状态”。您能否分享来自codesandbox.iojsbin.com 的完整代码
  • 这里是codeandbox的链接:codesandbox.io/embed/bold-mendel-hgvun

标签: reactjs react-router


【解决方案1】:

我认为函数表达式 PrivateRoute 是在使用 this.props.location.state 之后立即调用的。如果您使用的是函数表达式,则必须在使用前声明它。

也许你可以尝试在渲染方法之前声明函数表达式

 //Class Login:
 handleSubmit(event){
  event.preventDefault();
  var payload = {
    "email": this.state.email,
    "password": this.state.password
  }
  axios.post({url}"/login", payload)
  .then((res) => {
    console.log(res);
    if (res.data.status == "success") {
      auth.authenticate(() => {
        this.setState({ redirectToReferrer: true});
      });
      this.setState({authenticated: true});
      this.setState({token: res.data.data.token})
    }
}

// declare function expression here so that the interpreter reaches the code first before its being used
const PrivateRoute = ({ component: Component, authed, ...rest }) => (
<Route {...rest} render={(props) => (
  authed === true
    ? <Component {...props} />
    : <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }} />
)} />
);


render() {
  let {from} = this.props.location.state || {from: {pathname: '/'}};
  const { redirectToReferrer } = this.state;
  if (redirectToReferrer == true) {
    return <Redirect to={from} />
  }
  return (
          <form>
            <input value={this.state.email} onChange={this.handleChange} type="email" name="email" placeholder="Email" />
            <input value={this.state.password} onChange={this.handleChange} type="password" name="password" placeholder="Password" />
            <button type="submit" onClick={this.handleSubmit} className="btn btn-primary">Login</button>
          </form>
  );
}
  }

或者将函数表达式更改为常规函数可能会起作用!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-28
    • 2023-03-21
    • 2022-12-09
    • 2021-11-12
    • 2019-10-02
    • 1970-01-01
    • 2011-02-07
    • 2018-07-15
    相关资源
    最近更新 更多