Reaction路由V5

我正在try 构建一个简单的重定向,以便当用户try 访问受限URL时,它会将他们重定向到登录,登录后,它会将他们发送回他们所在的URL.例如:WebSite.com/设置受到保护,因此如果尚未登录,请重定向至登录.登录后,重定向回设置.这一直很有效,直到我最近重新嵌套了我的路由,包括布局.我假设我的重定向URL正在到达父路由,但我不确定如何将其向下传递到组件.

App.js:

                 <Switch>
                      <Route path="/password-reset/:reset_key?" exact>
                          <AuthLayout>
                              <PasswordReset />
                          </AuthLayout>
                      </Route>
                      <Route path="/register" exact>
                          <AuthLayout>
                              <Register />
                          </AuthLayout>
                      </Route>
                      <Route path="/login" exact>
                          <AuthLayout>
                              <Login />
                          </AuthLayout>
                      </Route>
                      {/* Other MainLayout routes */}
                      <Route>
                          <MainLayout>
                              <Switch>
                                  <Route path="/" exact component={Dashboard} />
                                  <Route path="/search" exact component={SearchResults} />
                                  <Route path="/user/:user_id" exact component={Profile} />
                                  <PrivateRoute path="/settings" exact component={Settings} />
                                  <Route path="/communities" exact component={CommunityDashboard} />
                                  <PrivateRoute path="/communities/new" exact component={CommunityNew} />
                                  <Route path="/communities/view/:community_id" exact component={CommunityView} />
                                  <PrivateRoute path="/communities/edit/:community_id" exact component={CommunityEdit} />
                                  <Route path='/404' component={Error404} />
                              </Switch>
                          </MainLayout>
                      </Route>
                      <Redirect from='*' to='/404' />
                  </Switch>

命中受保护的路由,将触发PrivateRouting功能:

const PrivateRoute = ({component: Component, path, auth, ...rest}) => (
<Route
{...rest}
render = {props =>
    auth.isAuthenticated === true ? (
        <Component {...props} />
    ) : (
        <Redirect to={{
            pathname: '/login',
            state: {
                redirectUrl: window.location.href.includes('login') ? '/' : window.location.href
            }
        }} />
    )
}
/>

);

我无法在我的代码中的任何地方访问这个.state.redirectUrl.这是我正在使用的布局页面.作为路径中的第一个嵌套组件,我想我至少会在那里看到它

import React  from 'react';
import './auth.css';
import PropTypes from "prop-types";
import {connect} from "react-redux";

class AuthLayout extends React.Component {

componentDidMount() {
    if(this.props.auth.isAuthenticated){
        this.props.history.push('/');
    }
}

render() {
    return (
        <div className="auth-background">
            <img
                alt=""
                className="logo"
                src={require("./logo1.png")}
            />
            <div id='auth-form'>
                {this.props.children}
            </div>
        </div>
    );

    }
}

AuthLayout.propTypes = {
    auth: PropTypes.object.isRequired
}

const mapStateToProps = (state) => ({
    auth: state.auth
});

export default connect(mapStateToProps, {})(AuthLayout);

登录页嵌套在Routing&gt;AuthLayout下.我需要在这里访问redirectUrl,这样我就可以传递给我的登录函数,并在成功登录后重定向:

class LoginForm extends React.Component {
constructor(props){
    super(props);
    this.state = {
        email: '',
        password: '',
        errors: {}
    }
}

handleSubmit = values => {
    const userData = {
        email: values.email,
        password: values.password
    };

    const redirectUrl = this.props.location ? this.props.location.state.redirectUrl : "/"

    this.props.loginUser(userData, redirectUrl, this.props.history);
};

render() {

    return (

推荐答案

当将JSX作为Route的子组件呈现时,路由属性不会传递给它们.

<Route path="/password-reset/:reset_key?" exact>
  <AuthLayout>        // <-- no route props
    <PasswordReset /> // <-- no route props
  </AuthLayout>
</Route>

使用renderprops 访问布线props ,并将其显式传递给AuthLayout和其他嵌套组件.

<Route
  path="/password-reset/:reset_key?"
  exact
  render={routeProps => (
    <AuthLayout {...routeProps}>
      <PasswordReset {...routeProps} />
    </AuthLayout>
  )}
/>

或者,你也可以用withRouter个高阶组件来装饰所有这些组件,以注入最近的Route英尺S路由props 作为props .

授权布局:

import React  from 'react';
import './auth.css';
import PropTypes from "prop-types";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";

class AuthLayout extends React.Component {
  componentDidMount() {
    if (this.props.auth.isAuthenticated) {
      this.props.history.push('/');
    }
  }

  render() {
    return (
      <div className="auth-background">
        <img
          alt=""
          className="logo"
          src={require("./logo1.png")}
        />
        <div id='auth-form'>
          {this.props.children}
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  auth: state.auth
});

export default withRouter(connect(mapStateToProps)(AuthLayout));

请注意,情况并非如此.

import { withRouter } from "react-router-dom";

class LoginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
      errors: {}
    }
  }

  handleSubmit = values => {
    const { history, location } = this.props;
    const { email, password } = values;
    const userData = { email, password };

    const redirectUrl = location?.state?.redirectUrl ?? "/";

    this.props.loginUser(userData, redirectUrl, history);
  };

  render() {
    ...
  }
}

export default withRouter(Login);

由于Reaction类组件实际上已被弃用,因此您还可以考虑将这些类组件转换为函数组件,并使用适当的Reaction-Router-DOM挂钩.

示例:

授权布局:

import React  from 'react';
import './auth.css';
import { useHistory } from "react-router-dom";
import { useSelector } from "react-redux";

const AuthLayout = ({ children }) => {
  const history = useHistory();

  const isAuthenticated = useSelector(state => state.auth.isAuthenticated);

  React.useEffect(() => {
    if (isAuthenticated) {
      history.push("/");
    }
  }, [history, isAuthenticated]);

  return (
    <div className="auth-background">
      <img
        alt=""
        className="logo"
        src={require("./logo1.png")}
      />
      <div id='auth-form'>
        {children}
      </div>
    </div>
  );
};

export default AuthLayout;

请注意,情况并非如此.

import { useDispatch } from "react-redux";
import { useHistory, useLocation } from "react-router-dom";

const LoginForm = () =>  {
  const dispatch = useDispatch();
  const history = useHistory();
  const { state } = useLocation();

  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [errors, setErrors] = React.useState({});

  const handleSubmit = values => {
    const { history, location } = this.props;
    const { email, password } = values;
    const userData = { email, password };

    const redirectUrl = state?.redirectUrl ?? "/";

    dispatch(loginUser(userData, redirectUrl, history));
  };

  return (
    ...
  );
}

export default Login;

另一种 Select 仍然是重构路由代码,以呈现与MainLayout类似的单个AuthLayout.

示例:

<Switch>
  <Route path={["/password-reset/:reset_key?", "/register", "/login"]}>
    <AuthLayout>
      <Switch>
        <Route path="/password-reset/:reset_key?" component={PasswordReset} />
        <Route path="/register" component={Register} />
        <Route path="/login" component={Login} />
      </Switch>
    </AuthLayout>
  </Route>
                      
  {/* Other MainLayout routes */}
  <Route>
    <MainLayout>
      <Switch>
        <Route path="/search" component={SearchResults} />
        <Route path="/user/:user_id" component={Profile} />
        <PrivateRoute path="/settings" component={Settings} />

        <Route path="/communities/view/:community_id" component={CommunityView} />
        <PrivateRoute path="/communities/edit/:community_id" component={CommunityEdit} />
        <PrivateRoute path="/communities/new" component={CommunityNew} />
        <Route path="/communities" component={CommunityDashboard} />

        <Route path='/404' component={Error404} />
        <Route path="/" exact component={Dashboard} />
        <Redirect from='*' to='/404' />
      </Switch>
    </MainLayout>
  </Route>
</Switch>

Reactjs相关问答推荐

避风港访问端口以包含Reaction应用程序

在Next.js中实现动态更改的服务器组件

无法从正在使用Reaction的Electron 商务store 项目中的购物车中删除项目

无法将react 路由状态从路由传递给子组件

Reaction-路由-DOM v6与v5

React-apexcharts 中的 Y 轴刻度不会动态更新符号

UseEffect 似乎不适用于页面的首次渲染

Chart.js如何go 除边框

将水平滚动视图添加到底部导航选项卡

在按钮单击中将动态参数传递给 React Query

FlatList 不在 React Native 中呈现项目

@react-three/postprocessing 没有匹配的从 three.module.js 导出以导入WebGLMultisampleRenderTarget

如何通过 React JS 中的映射将新元素添加到对象数据数组中

单元测试 useLoaderData() react-router v6 加载器函数

如何通过单击多个选项中的特定项目在模态上呈现不同的标题?

如何通过 Material ui select 使下拉菜单下拉

使用 yarn 编译 protobuf js 时出现错误pbjs: command not found

为什么我在运行一些 npm react 命令时会收到这些警告?

单击三个按钮之一后如何显示特定按钮的内容?单击其中一个按钮后应隐藏所有按钮

多次响应获取发送请求