无法读取未定义的属性“isAuthenticated”

时间:2021-04-27 08:10:31

标签: reactjs redux mern

TypeError: 无法读取未定义的属性“isAuthenticated” Function.mapStateToProps [作为 mapToProps] E:/smnd/client/src/components/auth/Login.js:69

function mapStateToProps (state){
      return{
        isAuthenticated: state.auth.isAuthenticated
      }
    }

这是Login.js的代码

import React, {Fragment, useState } from 'react';
import {Link, Redirect} from 'react-router-dom';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import {login} from '../../actions/auth';
// import {isAuthenticated} from '../../reducers/auth';

 

const Login = ({login, isAuthenticated}) => {
    const [formData, setFormData] = useState({
        email: '',
        password: ''
    });

    const { email, password} = formData;

    const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });

    const onSubmit = async e => {
        e.preventDefault();
           login(email,password);
    };
    
    // redirected if logged in 
    if (isAuthenticated) {
      return <Redirect to='/dashboard' />;
    }
  

    return (
        <Fragment>
            <h1 className="large text-primary">Sign In</h1>
      <p className="lead"><i className="fas fa-user"></i> Sign Into Your Account</p>
      <form className="form" onSubmit={e => onSubmit(e)}>
        <div className="form-group">
          <input type="email" placeholder="Email Address" name="email" value={email} onChange={ e => onChange(e)}  />
        </div>
        <div className="form-group">
          <input
            type="password"
            placeholder="Password"
            name="password"
            value={password}
            onChange={ e => onChange(e)} 
            
          />
        </div>
        <input type="submit" className="btn btn-primary" value="Login" />
      </form>
      <p className="my-1">
        Don't have an account? <Link to="/register">Sign Up</Link>
      </p>
        </Fragment>
        );
    };

    Login.propTypes = {
      login: PropTypes.func.isRequired,
      isAuthenticated: PropTypes.bool
    }

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

     function mapStateToProps (state){
      return{
        isAuthenticated: state.auth.isAuthenticated
      }
    }

export default connect(mapStateToProps, {login}) (Login);

2 个答案:

答案 0 :(得分:1)

因为你没有在 redux store 中设置 auth 的初始状态。所以你需要像这样添加可选的链接:

isAuthenticated: state.auth?.isAuthenticated

答案 1 :(得分:1)

确保在 redux store 的 login reducer 中,您提供了“isAuthenticated”作为初始状态,如下所示..

const initialState = { isAuthenticated:假, };

function loginReducer(state = initialState, action){ .... }

如果您为您的 redux 存储使用多个reducer,还要确保您在“combineReducers”函数中包含了 loginReducer