如何将值传递给路线中的另一个组件?

时间:2018-10-08 15:30:40

标签: reactjs react-router

我有一个登录页面,该页面通过令牌进行身份验证,不久之后,输入的用户名和密码将返回用户数据。之后,我将用户重定向到名为“仪表板”的组件。但是我想将他的数据传递给该组件。

Index.js

我在这里创建了路线

import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import * as serviceWorker from './serviceWorker';
    import Sobre from './Sobre.js';
    import { BrowserRouter, Switch, Route } from 'react-router-dom';
    import Dashboard from './ui/Dashboard';
    import LoginForm from './ui/LoginForm';

    ReactDOM.render(
        <BrowserRouter>
            <Switch>
                <Route path="/" exact={true} component={LoginForm} />
                <Route path="/sobre" component={Sobre} />
                <Route path="/dashboard" component={Dashboard} />
            </Switch>
        </BrowserRouter>
         ,document.getElementById('root'));

    // If you want your app to work offline and load faster, you can change
    // unregister() to register() below. Note this comes with some pitfalls.
    serviceWorker.register();

登录页面

在isUser函数中,它被重定向到仪表板。无论是否是用户,都缺少条件,但事实并非如此。

import React, { Component } from 'react';


    export default class LoginForm extends Component{

        constructor(){
            super();

            this.state = {
                login: '',
                senha: '',
                authenticate_code: '',
                url: 'http://192.168.0.19/api/'         
            };

            this.handleLogin = this.handleLogin.bind(this);
            this.isUser = this.isUser.bind(this);
        }

        handleLogin(e){

            e.preventDefault();

            let dataToGetToken= {
                nome: "teste",
                senha: "1234"
            };

            try{
                fetch(this.state.url + 'token', {
                  method: 'POST',
                  body: JSON.stringify(dataToGetToken),
                  headers: {
                    "Content-type": "application/json; charset=UTF-8"
                  } 
                })
                .then(response => response.json())
                .then(json => { 
                    this.setState({ authenticate_code: 'bearer ' + json.token })
                    this.isUser(this.refs.login.value, this.refs.pass.value, this.state.authenticate_code);
                });
            }
            catch(e){
              console.log(e);
            }

        }

        isUser(name, pass, token){

            var login = new Object();
            login.nome = name;
            login.senha = pass;
            console.log(login);
            console.log(token);
            try{
                fetch(this.state.url + 'usuarios/getuser', {
                  method: 'POST',
                  body: JSON.stringify(login),
                  headers: {
                    "Authorization": token,
                    "Content-type": "application/json; charset=UTF-8"
                  } 
                })
                .then(response => response.json())
                .then(json => { 
                    //Redireciona
                    this.props.history.push('/ui/Dashboard')
                });
            }
            catch(e){
              console.log(e);
            }

        }

        render(){
            return(
                <div className="App">
                    <div className="container">
                        <div className="row">
                            <div className="col-sm-12">
                                <form onSubmit={this.handleLogin}>
                                      <div className="form-group">
                                        <label htmlFor="exampleInputEmail1">Login</label>
                                        <input type="text" ref="login" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"/>
                                        <small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
                                      </div>
                                      <div className="form-group">
                                        <label htmlFor="exampleInputPassword1">Senha</label>
                                        <input type="password" ref="pass" className="form-control" id="exampleInputPassword1" placeholder="Password" />
                                      </div>
                                      <div className="form-group form-check">
                                        <input type="checkbox" className="form-check-input" id="exampleCheck1" />
                                        <label className="form-check-label" htmlFor="exampleCheck1">Check me out</label>
                                      </div>
                                      <button type="submit" className="btn btn-primary">Submit</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                );
        }
    }

** 我想重定向到此组件,但我想获取登录名返回的数据**

import React, { Component } from 'react';

    export default class Dashboard extends React.Component {

        constructor(props) {
            super(props);
        }

        render() {
            return (
                <div></div>
            );
        }
    }

2 个答案:

答案 0 :(得分:1)

我认为,对于您来说,为了在推动路线时传递一些道具,您只需执行以下操作:

this.props.history.push('/ui/Dashboard', { prop : 'value' })

您可以查看示例right here

答案 1 :(得分:1)

您始终可以使用Route's render declaration

将道具向下传递到子组件中
<Route render={() => <Sobre props={this.props} />} />