React router v4 - 如何访问通过Redirect传递的状态?

时间:2017-10-22 17:07:23

标签: reactjs redirect react-router react-redux

我正在使用react的帮助创建一个登录页面,当登录成功时,该页面会重定向到另一个页面。让我调用登录成功后呈现的组件' A'。我想将从数据库中提取的数据传递给组件A,我这样做是通过将其传递到“状态”来实现的。 '重定向'的属性零件。但是,我不明白如何在' Route'中访问此状态。最终呈现组件A的组件。任何人都可以告诉我如何?

我的代码如下:

Login.js:

import React from 'react'
import Center from 'react-center'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import isEmpty from 'lodash/isEmpty'
import { browserHistory } from 'react-router'
import { Route, Redirect } from 'react-router-dom'

import Courses from '../pages/Courses'
import Logo from './shared/Logo'
import Routes from './Routes'
import Tiles from './Tiles'

export default class LoginForm extends React.Component
{
    constructor()
    {
        super()

        this.state = 
        {
            username: '',
            password: '',
            student: false,
            instructor: false,
            error_password: '',
            error_username: ''
        }

        this.onChange = this.onChange.bind(this)
        this.onSubmit = this.onSubmit.bind(this)
    }

    onChange(event)
    {
        this.setState({error_username:'', error_password:'', [event.target.name]: event.target.value})
        console.log(this.state)
        event.preventDefault()
    }

    onSubmit(event)
    {
        event.preventDefault()
        if (this.state.username && this.state.password)
        {
            this.props.loginRequest({username: this.state.username, password: this.state.password})
            .then(response => 
                {
                    this.setState(    // THE SERVER WILL SEND THE RELEVANT DATA HERE
                    {
                        username: '',
                        password: '',
                        student: response.data.student, 
                        error_username: response.data.error_username, 
                        error_password: response.data.error_password
                    })
                })
        }
        else
            this.setState({error_username: 'Please enter username', error_password: 'Please enter password.'})
    }

    render()
    {
        const styles =
        {
            buttonStyle:
            {
                margin: 'auto',
                width: '83'
            }
        }

        if (this.state.student)  ///  REDIRECT IS HAPPENING HERE
        {
            return (
            <Redirect to = {{
                pathname: '/loginS/student',
                state: { course_information }  /// HERE I WILL SEND THE RELEVANT INFORMATION THAT THE SERVER SENDS TO THE COMPONENT A 
            }}/> )
        }
        else if (this.state.instructor)
        {
            return <Redirect to = {'/loginI/instructor'} />
        }
        else 
        {
            // NOT RELEVANT
        }

        return(

            display 
        )
    }
}

LoginForm.propTypes = 
{
    loginRequest: PropTypes.func.isRequired
}

Routes.js

import React from 'react'
import { Switch, Route } from 'react-router-dom'

import Courses from '../pages/Courses'
import Login from './Login'
import Dashboard from './Dashboard'
import StudentsHandle from './StudentsHandle'
import CourseItem from './CourseItem'
import SemesterItem from './SemesterItem'
import Logo from './shared/Logo'
import Tiles from './Tiles'

export default class Routes extends React.Component
{
    render() 
    {
        return(
            <Switch>
                <Route exact path = '/' component = { Dashboard }/>
                <Route exact path = '/loginS' component = { Login } />
                <Route path = '/loginS/student' render = { (props) =>  < Tiles data = {this.props.coursesData} />} /> // HOW DO I ACCESS THE PROPS REDIRECT SENDS HERE?
                <Route path = '/instructor' component = { Courses } />
            </Switch>
        );
    }
} 

3 个答案:

答案 0 :(得分:14)

您可以使用location道具来访问您已通过的州。访问React-Router以获取参考。如果要访问该状态,可以this.props.location.state

执行此操作

答案 1 :(得分:2)

如果您使用 React 钩子,则可以使用 useLocation 钩子。

import { useLocation } from 'react-router-dom';

export const MyComponent = () => {
  const { state } = useLocation();

  ...
} 

答案 2 :(得分:0)

您可以使用let parser = new DOMParser() let doc = parser.parseFromString(str, "text/html") doc .querySelectorAll('*') .forEach(node => { console.log(node); });

访问状态