TypeError: Cannot read properties of undefined (reading 'setIsAuth')

TypeError: Cannot read properties of undefined (reading 'setIsAuth')

我收到错误:“Login.js:12 未捕获(承诺)TypeError:无法读取未定义的属性(读取 'setIsAuth')”

这是我的Login.js

import React from 'react';
import { auth, provider } from '../firebaseconf';
import { signInWithPopup } from 'firebase/auth';
import { useNavigate } from 'react-router-dom';

function Login({ setIsAuth }) {
    let navigate = useNavigate();

    const singInWithGoogle = () => {
        signInWithPopup(auth, provider).then((result) => {
            localStorage.setItem("isAuth", true);
            setIsAuth(true);
            navigate("/");
        });
    };

    return (
        <div>
            <button onClick={singInWithGoogle}>Sign in with Google</button>
        </div>
    );

}
export default Login;

还有我的App.js


import React, { Component } from 'react';
import './css/main.css';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './pages/Home';
import CreatePost from './pages/CreatePost';
import Login from './pages/Login';


class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isAuth: false,
      setIsAuth: false
    };
  }

  render() {
    return (
      <Router>
        <nav>
          <Link to="/">Home</Link>
          <Link to="/createpost"> Create New Post</Link>
          {!this.state.isAuth && <Link to="/login">Login</Link>}
        </nav>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/login" element={<Login setIsAuth={this.state.setIsAuth} />} />
          <Route path="/createpost" element={<CreatePost />} />
        </Routes>
      </Router>
    );
  }
}

export default App;

我认为我已经在 App.js 构造函数中定义了它,寻求您的帮助,谢谢

login.js 中你使用 setIsAuth 就好像它是一个函数但不是函数,它是一个在你的 App.js 中设置为 false 的变量。要更改 this.state.setIsAuth 的值,您应该这样做:


App.js

signIn = () => {
  this.setState({ setIsAuth: true });
}

<Route path="/login" element={<Login setIsAuth={this.signIn} />} />


Login.js

signInWithPopup(auth, provider).then((result) => {
  localStorage.setItem("isAuth", true);
  setIsAuth();
  navigate("/");
});