GVKun编程网logo

如何在Reactjs的新的react-router-dom中使用重定向(react路由重定向)

10

对于想了解如何在Reactjs的新的react-router-dom中使用重定向的读者,本文将是一篇不可错过的文章,我们将详细介绍react路由重定向,并且为您提供关于ReactMaterialUI+

对于想了解如何在Reactjs的新的react-router-dom中使用重定向的读者,本文将是一篇不可错过的文章,我们将详细介绍react路由重定向,并且为您提供关于React Material UI + React Router >>>>我不能在按钮的onClick函数中使用重定向、reactjs – React Router DOM – 如何在每个页面上包含导航栏?、reactjs – React Router v4重定向表单提交、reactjs – React Router将IndexRoute重定向到正确的路径的有价值信息。

本文目录一览:

如何在Reactjs的新的react-router-dom中使用重定向(react路由重定向)

如何在Reactjs的新的react-router-dom中使用重定向(react路由重定向)

我正在使用最新版本的react-router模块,名为react-router-
dom,它已成为使用React开发Web应用程序时的默认模块。我想知道在POST请求后如何进行重定向。我一直在编写此代码,但是在请求之后,什么都没有发生。我在网上查看过,但是所有数据都是关于React
Router的先前版本的,而关于最后一个更新的则不是。

码:

import React, { PropTypes } from ''react'';import ReactDOM from ''react-dom'';import { BrowserRouter } from ''react-router-dom'';import { Redirect } from ''react-router''import SignUpForm from ''../../register/components/SignUpForm'';import styles from ''./PagesStyles.css'';import axios from ''axios'';import Footer from ''../../shared/components/Footer'';class SignUpPage extends React.Component {  constructor(props) {    super(props);    this.state = {      errors: {},      client: {        userclient: '''',        clientname: '''',        clientbusinessname: '''',        password: '''',        confirmPassword: ''''      }    };    this.processForm = this.processForm.bind(this);    this.changeClient = this.changeClient.bind(this);  }  changeClient(event) {    const field = event.target.name;    const client = this.state.client;    client[field] = event.target.value;    this.setState({      client    });  }  async processForm(event) {    event.preventDefault();    const userclient = this.state.client.userclient;    const clientname = this.state.client.clientname;    const clientbusinessname = this.state.client.clientbusinessname;    const password = this.state.client.password;    const confirmPassword = this.state.client.confirmPassword;    const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };    axios.post(''/signup'', formData, { headers: {''Accept'': ''application/json''} })      .then((response) => {        this.setState({          errors: {}        });        <Redirect to="/"/> // Here, nothings happens      }).catch((error) => {        const errors = error.response.data.errors ? error.response.data.errors : {};        errors.summary = error.response.data.message;        this.setState({          errors        });      });  }  render() {    return (      <div className={styles.section}>        <div className={styles.container}>          <img src={require(''./images/lisa_principal_bg.png'')} className={styles.fullImageBackground} />          <SignUpForm             onSubmit={this.processForm}            onChange={this.changeClient}            errors={this.state.errors}            client={this.state.client}          />          <Footer />        </div>      </div>    );  }}export default SignUpPage;

答案1

小编典典

您必须使用setState设置一个属性,该属性将呈现<Redirect>您的render()方法内部。

例如

class MyComponent extends React.Component {  state = {    redirect: false  }  handleSubmit () {    axios.post(/**/)      .then(() => this.setState({ redirect: true }));  }  render () {    const { redirect } = this.state;     if (redirect) {       return <Redirect to=''/somewhere''/>;     }     return <RenderYourForm/>;}

就是说,我建议您将API调用放在服务之内。然后,您可以使用该history对象以编程方式进行路由。这就是与redux集成的工作方式。

但是我想您有这样做的理由。

React Material UI + React Router >>>>我不能在按钮的onClick函数中使用重定向

React Material UI + React Router >>>>我不能在按钮的onClick函数中使用重定向

您可以通过两种方法重定向用户:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> useHistory

useHistory挂钩

如果您想在点击时直接重定向用户,则可以强制性地对待代码,并告诉React 做什么

<Redirect />

更多信息https://reactrouter.com/web/api/Hooks/usehistory

重定向组件

或者,如果您对使用React的默认声明式模型感到更自在,则可以说出更改了,并允许您的代码对此更改做出反应

const history = useHistory();
    
const handleMenuItemClick = (event,index) => {
    setSelectedIndex(index);
    setOpen(false);
    history.push(`/groups/${index}`)
};
    

更多信息https://reactrouter.com/web/api/Redirect

reactjs – React Router DOM – 如何在每个页面上包含导航栏?

reactjs – React Router DOM – 如何在每个页面上包含导航栏?

我的App.js组件中有这个代码:

render() {
        return (
            <div>
                <Navbar/>
                <browserRouter>
                    <Switch>
                        <Route exact path="/" component={Home}/>
                        <Route path="/about" component={About} />                         
                        <Route path="*" render={() => <Redirect to="/" />} />
                    </Switch>
                </browserRouter>
            </div>
        );
    }

现在我尝试在我的一个其他组件中包含一个Link组件,但我发现browserRouter必须是App.js组件的根元素,以便它可以工作.现在我想知道如果我还想在每个页面上都包含导航栏,我将如何将其作为路由元素.

解决方法

您应该可以将它放在< Switch>之外.零件.

<browserRouter>
    <div>
        <Navbar/>
        <Switch>
            <Route exact path="/" component={Home}/>
            <Route path="/about" component={About} />                         
            <Route path="*" render={() => <Redirect to="/" />} />
        </Switch>
    </div>
</browserRouter>

reactjs – React Router v4重定向表单提交

reactjs – React Router v4重定向表单提交

全新的反应,尝试在“登录”页面上单击提交后重定向到“主页”.试图按照路由器反应教程.

当我单击表单和控制台上的提交按钮记录状态和fakeAuth.isAuthenticated时,它们都返回true.但是,重定向未触发.

Login.js

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

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


    handleSubmit(e) {
        fakeAuth.authenticate(() => {
            this.setState({
                portalId: this.refs.portalId.value,password: this.refs.password.value,redirectToReferrer: true
            })
        })
        e.preventDefault();
    }


    render() {
        const redirectToReferrer = this.state.redirectToReferrer;
        if (redirectToReferrer === true) {
            <Redirect to="/home" />
        }

Routes.js

export const fakeAuth = {
    isAuthenticated: false,authenticate(cb) {
        this.isAuthenticated = true
        setTimeout(cb,100)
    },signout(cb) {
        this.isAuthenticated = false
        setTimeout(cb,100)
    }
}

const PrivateRoute = ({ component: Component,...rest }) => (
    <Route {...rest} render={() => (
        fakeAuth.isAuthenticated === true
        ? <Component {...this.props}/>
        : <Redirect to="/" />
    )}/> 
)


export default () => (
    <browserRouter>
        <div>
            <Navbar />
            <Switch>
                <Route path="/" exact component={Login} />
                <Route path="/register" exact component={Register} />
                <Route path="/home" exact component={Home} />
            </Switch>
        </div>
    </browserRouter>
);

解决方法

您必须在render方法中返回Redirect(否则它将不会被渲染,因此不会发生重定向):

render() {
        const redirectToReferrer = this.state.redirectToReferrer;
        if (redirectToReferrer === true) {
            return <Redirect to="/home" />
        }
        // ... rest of render method code
   }

reactjs – React Router将IndexRoute重定向到正确的路径

reactjs – React Router将IndexRoute重定向到正确的路径

我正在尝试配置React Router,以便在访问 http://url/manage/roomId时直接转到 http://url/manage/roomId/sessions(加载RoomSessions组件).这些是标签组件的路由,我想默认使用正确的URL(它没有)加载第一个标签的内容(它所做的).

除重定向外,它工作正常

<Route path=''manage/:roomId'' component={RoomsManagerManageRoom} onEnter={requireAuth}>
                        <IndexRoute component={RoomSessions} onEnter={requireAuth} />
                        <Route path=''sessions'' component={RoomSessions} onEnter={requireAuth} />
                        <Route path=''meetings'' component={RoomMeetings} onEnter={requireAuth} />
                        <Route path=''files'' component={RoomFiles} onEnter={requireAuth} />
                        <Route path=''recordings'' component={Roomrecordings} onEnter={requireAuth} />
                        <Route path=''sections'' component={RoomSections} onEnter={requireAuth} />
                        <Route path=''hosts'' component={RoomHosts} onEnter={requireAuth} />
                    </Route>

我错过了什么?

解决方法

替换< IndexRoute />与…一致

<IndexRedirect to="sessions" />

我们今天的关于如何在Reactjs的新的react-router-dom中使用重定向react路由重定向的分享已经告一段落,感谢您的关注,如果您想了解更多关于React Material UI + React Router >>>>我不能在按钮的onClick函数中使用重定向、reactjs – React Router DOM – 如何在每个页面上包含导航栏?、reactjs – React Router v4重定向表单提交、reactjs – React Router将IndexRoute重定向到正确的路径的相关信息,请在本站查询。

本文标签: