属性未定义-在React中从类组件切换到函数挂钩组件

拉杜·克里斯蒂安·沃恩

尝试将Bootcamp项目代码从类组件切换到有状态功能组件时遇到此错误:

TypeError: Cannot read property 'user' of undefined
(anonymous function)
C:/Proiect curs react/src/pages/Login/Login.jsx:35
  32 | // }
  33 | 
  34 | useEffect((prevProps) => {
> 35 |  if (props.user !== prevProps.user) {
     | ^  36 |      props.history.push("/");
  37 |  }
  38 | }, [props.user, props.history]);

这发生在Login组件中,该组件负责显示使用Firebase服务通过Google连接的选项,并重定向到主页,这是useEffect试图做的。

下面的代码中注释了componentDidUpdate方法的代码,该方法正是在该组件是一个类时执行的。

import React, { useEffect } from "react";
import { Link } from "react-router-dom";
import Logo from "../../assets/images/logo.png";
import { ReactComponent as Google } from "../../assets/icons/google.svg";
import "./Login.css";
import { connect } from "react-redux";
import { loginUser } from "../../redux/actions/user";

const Login = (props) => {
    // componentDidUpdate(prevProps) {
    //     if (this.props.user !== prevProps.user) {
    //         this.props.history.push('/');
    //     }
    // }

    useEffect((prevProps) => {
        if (props.user !== prevProps.user) {
            props.history.push("/");
        }
    }, [props.user, props.history]);

    return (
        <div className="login-page">
            <Link to="/">
                <img src={Logo} alt="logo" className="mb-5" />
            </Link>
            <h1 className="h2">Login</h1>
            <p>Alege providerul cu care vrei să vrei să te loghezi:</p>
            <button
                className="btn btn-outline-dark d-flex align-items-center"
                onClick={() => props.signInWithGoogle()}
            >
                <Google className="w-50 mr-3" />
                <span className="text-nowrap">Loghează-te cu Google</span>
            </button>
        </div>
    );
};

function mapStateToProps(state) {
    return {
        user: state.user.data,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        signInWithGoogle: () => dispatch(loginUser()),
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);

另外,下面是指向包含整个应用程序的github存储库的链接。

https://github.com/vradu007/radu-shop

如果您能告诉我我做错了什么,请告诉我-我尚未在训练营中研究过钩子,但是我在工作中使用钩子,并且我一直在试图从网上了解它。谢谢!

编辑:使用该答案,我得到以下错误:

./src/pages/Login/Login.jsx
  Line 10:17:  React Hook "useRef" is called in function "getPrevious" which is neither a React function component or a custom React Hook fun
ction     react-hooks/rules-of-hooks
  Line 11:5:   React Hook "useEffect" is called in function "getPrevious" which is neither a React function component or a custom React Hook 
function  react-hooks/rules-of-hooks

无论我是否导入useRef,都会重现该错误。当前组件看起来像这样:

import React, { useEffect, useRef } from "react";
import { Link } from "react-router-dom";
import Logo from "../../assets/images/logo.png";
import { ReactComponent as Google } from "../../assets/icons/google.svg";
import "./Login.css";
import { connect } from "react-redux";
import { loginUser } from "../../redux/actions/user";

function getPrevious(value) {
    const ref = useRef();
    useEffect(() => {
        ref.current = value;
    });
    return ref.current;
}

const Login = (props) => {
    // componentDidUpdate(prevProps) {
    //     if (this.props.user !== prevProps.user) {
    //         this.props.history.push('/');
    //     }
    // }
    
    const { user, history } = props;
    const previous = getPrevious({ user, history });
    useEffect(
        (prevProps) => {
            if (props.user !== previous.user) {
                props.history.push("/");
            }
        },
        [props.user, props.history]
    );

    return (
        <div className="login-page">
            <Link to="/">
                <img src={Logo} alt="logo" className="mb-5" />
            </Link>
            <h1 className="h2">Login</h1>
            <p>Alege providerul cu care vrei să vrei să te loghezi:</p>
            <button
                className="btn btn-outline-dark d-flex align-items-center"
                onClick={() => props.signInWithGoogle()}
            >
                <Google className="w-50 mr-3" />
                <span className="text-nowrap">Loghează-te cu Google</span>
            </button>
        </div>
    );
};

function mapStateToProps(state) {
    return {
        user: state.user.data,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        signInWithGoogle: () => dispatch(loginUser()),
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);
拉杜·克里斯蒂安·沃恩

最后,我设法通过添加一个布尔值来解决此问题,该值将检查是否需要重定向并将其存储在状态中-难看但有些有效。

import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import Logo from "../../assets/images/logo.png";
import { ReactComponent as Google } from "../../assets/icons/google.svg";
import "./Login.css";
import { connect } from "react-redux";
import { loginUser } from "../../redux/user/userAction";

const Login = (props) => {

    const [redirect, changeRedirect] = useState(false);
    const { user, history, signInWithGoogle } = props;
    useEffect(() => {
        if(redirect){
            history.push("/");
        }
    }, [user, history]);

    const handleClick = () => {
        changeRedirect(true);
        signInWithGoogle();
    }

    return (
        <div className="login-page">
            <Link to="/">
                <img src={Logo} alt="logo" className="mb-5" />
            </Link>
            <h1 className="h2">Login</h1>
            <p>Alege providerul cu care vrei să vrei să te loghezi:</p>
            <button
                className="btn btn-outline-dark d-flex align-items-center"
                onClick={() => handleClick()}
            >
                <Google className="w-50 mr-3" />
                <span className="text-nowrap">Loghează-te cu Google</span>
            </button>
        </div>
    );
};

function mapStateToProps(state) {
    return {
        user: state.user.data,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        signInWithGoogle: () => dispatch(loginUser()),
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

未定义反应组件的属性

来自分类Dev

React组件中的“无法读取未定义的属性'onClick'”

来自分类Dev

React无法读取未定义的属性

来自分类Dev

在AngularJS中对象属性未定义

来自分类Dev

别名属性在Route中未定义

来自分类Dev

在AngularJS中对象属性未定义

来自分类Dev

“ hasOne”关系中的未定义属性

来自分类Dev

属性返回表中未定义的

来自分类Dev

打字稿中未定义的属性

来自分类Dev

`this` 的属性在 setTimeout 中未定义

来自分类Dev

Angular 2-组件属性在方法中未定义

来自分类Dev

无法读取功能组件中未定义的属性“ props”

来自分类Dev

Vue - 子组件中未定义属性(对象)

来自分类Dev

AngularJS 2组件属性未定义

来自分类Dev

Vue组件属性或方法“ x”未定义

来自分类Dev

TypeScript样式化组件主题属性返回未定义

来自分类Dev

为什么我的子vuejs组件属性未定义?

来自分类Dev

组件YiiBooster datepickerRow错误:属性。*未定义

来自分类Dev

嵌套子组件未定义的输入属性

来自分类Dev

从父类访问属性时未定义的属性

来自分类Dev

从父类访问属性时未定义的属性

来自分类Dev

TypeError:无法读取未定义的React类组件的属性'prototype'

来自分类Dev

Axios在React中未定义,错误:Uncaught TypeError:无法读取未定义的属性“ post”

来自分类Dev

无法解构“未定义”的属性“历史”,因为它未定义。--React.js

来自分类Dev

无法读取未定义的属性“ disable”:Ivy中未定义this.ngControl.control

来自分类Dev

切片节点结构中的未定义属性

来自分类Dev

PHP类的动态变量中的未定义属性

来自分类Dev

php中带有类的未定义属性

来自分类Dev

无法读取类中未定义的属性

Related 相关文章

热门标签

归档