微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决无法读取未定义的属性“isAuthenticated”

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);

解决方法

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

isAuthenticated: state.auth?.isAuthenticated
,

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

const initialState = { isAuthenticated:假, };

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。