【问题标题】:React Router render vs component giving me error反应路由器渲染与组件给我错误
【发布时间】:2019-12-25 06:07:33
【问题描述】:

我正在尝试使用此处显示的反应路由器身份验证重定向 (https://reacttraining.com/react-router/web/example/auth-workflow)。我目前收到错误无法接收未定义的属性“状态”。

错误出现在我的登录组件中,该组件当前在 React Router 中通过 Route path="/login" render={() => Login } exact 调用。但是当我将它更改为Route path="/login" component={Login} exact 时,它会呈现并且不会给我错误。我确实需要使用渲染函数,因为我需要它来进行回调。关于它为何如此行事的任何想法。

function Protected() {
  return <h3>Protected</h3>;
}
function AuthExample() {
  return (
<React.Fragment>
  <Router>
    <Switch>
      <Route path="/login" component={Login} exact />
      <PrivateRoute path="/" render={() => <Protected />} exact />
    </Switch>
  </Router>
</React.Fragment>
  );
}

class Login extends Component {
  constructor(props) {
super(props);
this.state = {
  redirectToReferrer: false,
};
}

handleSubmit(event) {
fakeAuth.authenticate(() => {
  this.setState({ redirectToReferrer: true });
});
}

render() {
const { from } = this.props.location.state || { from: { pathname: "/" } };
const { redirectToReferrer } = this.state;
if (redirectToReferrer === true) {
  this.props.history.push(from.pathname);
}
return (
  <button
    type="submit"
    onClick={this.handleSubmit}
    className="btn btn-primary"
  >
    Login
  </button>
);
}
}

我还直接从上面提供的链接中获取了 fakeAuth 和 PrivateRoute。这是代码框的链接:https://codesandbox.io/s/dawn-cherry-3yv8e?fontsize=14。 当我单击登录时,作为一种附带任务,它不会将我重定向到受保护的页面。感谢您的帮助。

【问题讨论】:

    标签: reactjs authentication react-router-dom


    【解决方案1】:

    您忘记使用 withRouter 包装您的组件

    export default withRouter(Login);
    

    注意: 在你的帖子中你写了这个

    Route path="/login" render={() => Login } exact 
    

    这是错误的(除非是错字),应该是,

    <Route path="/login" render={() => <Login /> } exact />
    

    【讨论】:

    • 是的,出于某种原因,如果在文本中使用 '>' 很抱歉,其中的所有内容都不会出现在文章中,所以我决定去掉它。不过感谢您的提醒。
    • 您应该注意到您的帖子中的render={() =&gt; Login } 和我的回答中的render={() =&gt; &lt;Login /&gt; }
    • 感谢您的帮助,我让自己陷入了其他错误,但我克服了第一个障碍。
    【解决方案2】:

    未定义的东西很可能是“this.props.location”。你还记得将组件包装在“withRouter”中吗?如果没有,您将无法访问它。

    【讨论】:

      猜你喜欢
      • 2022-10-23
      • 1970-01-01
      • 2017-12-23
      • 2018-07-26
      • 2019-04-25
      • 2023-04-03
      • 2018-06-02
      • 1970-01-01
      • 2016-02-24
      相关资源
      最近更新 更多