将数据从获取传递到另一个组件

时间:2019-04-24 15:54:44

标签: reactjs

我有一个Login组件,该组件的表单带有用于用户数据的输入,并且我有一个带fetch的onFormSubmit方法。问题是我不知道如何将令牌传递到另一个组件(它在那里,我可以console.log它)。我想将令牌传递给另一个组件的原因是,另一个组件正在验证用户是否已登录并通过检测令牌(null =用户未登录并将其重定向到登录页面,否则转到受保护的页面)。< / p>

我的login.js组件

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

    onInputChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        });
    };

    onFormSubmit = (e) => {
        e.preventDefault();
        fetch('http://localhost:3001/user/login', {
            method: 'POST',
            body: JSON.stringify({
                email: this.state.email,
                password: this.state.password
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then( res => {
                if( res.status === 200){
                    this.props.history.push('/MyPlaces');
                } else {
                    const error = new Error(res.error);
                    throw error;
                }
            })
            .catch(err => {
               console.error(err);
               alert('Error login in please try again!');
            });
    };

    render() {
        return (
            <div className="loginPanel">
                <form onSubmit={this.onFormSubmit}>
                    <label>Email
                    <input type="text"
                           id="email"
                           value={this.state.email}
                           onChange={this.onInputChange}
                    />
                    </label>
                    <label>Password
                    <input type="text"
                           id="password"
                           value={this.state.password}
                           onChange={this.onInputChange}/>
                    </label>
                    <input type="submit" value="Submit" />
                </form>
            </div>
        );
    };
}

export default Login;

我的身份验证组件

import React, {Component} from 'react';
import { Redirect } from 'react-router-dom';

export default function withAuth(ComponentToProtect, props) {
    return class extends Component {
        constructor() {
            super();
            this.state = {
                loading: true,
                redirect: false
            };
        }

        componentDidMount() {
            fetch('')
                .then(res => {
                if( res.status === 200) {
                    this.setState({ loading: false});
                } else {
                    const error = new Error(res.error);
                    throw error;
                }
            })
                .catch(err => {
                    console.error(err);
                    this.setState({ loading: false, redirect: true });
                })
        }

        render() {
            const { loading, redirect } = this.state;
            if( loading ){
                return null;
            }
            if( redirect ){
                return <Redirect to="/Login" />;
            }

            return (
                <React.Fragment>
                    <ComponentToProtect {...this.props}/>
                </React.Fragment>
            );
        }
    }
}

我知道身份验证组件中的获取没有任何内容,我认为我应该再发起一个api请求(与登录组件中的请求相同,然后在获取后仅调用

.then(res => res.json()).then(res => {
    let token = res.token;
    console.log("token: ", token);
});

但是我认为这似乎不是一个好主意。您能否给我一些指导,我该怎么做?

1 个答案:

答案 0 :(得分:0)

获取后,您可以简单地使用localStorage.setItem('token-name', token);来存储令牌。然后,您可以使用localStorage.getItem('token-name')在所有组件中进行检索。如果getItem返回null,则只需重定向即可登录。

要注销,您只需将令牌值更新为null

登录组件

fetch('http://localhost:3001/user/login', {
    method: 'POST',
    body: JSON.stringify({
        email: this.state.email,
        password: this.state.password
    }),
    headers: {
        'Content-Type': 'application/json'
    }
})
.then(res => {
    if( res.status === 200){
        localStorage.setItem('token', res.token); //storing the token in localStorage.
        this.props.history.push('/MyPlaces');
    } else {
        const error = new Error(res.error);
        throw error;
    }
})
.catch(err => {
   console.error(err);
   alert('Error login in please try again!');
});

身份验证组件

componentDidMount() {
   let token = localStorage.getItem('token');  //retriving the token from localStorage
   if(token === null){
       this.setState({ loading: false, redirect: true });
   }        
}

希望这会对您有所帮助。