简体   繁体   English

TypeError:无法读取 React function 中未定义的属性“道具”

[英]TypeError: Cannot read property 'props' of undefined In a React function

I have a userContext that is authenticating the user.我有一个正在对用户进行身份验证的 userContext。 It is working, but after successful login I want the user to be directed to the /dashboard.它正在工作,但在成功登录后,我希望将用户定向到 /dashboard。 so I'm using this.props.history.push('/dashboard');所以我使用this.props.history.push('/dashboard'); but I'm getting the below error.但我收到以下错误。

TypeError: Cannot read property 'props' of undefined TypeError:无法读取未定义的属性“道具”

Is there a better way to do this?有一个更好的方法吗? While using a function?在使用 function 时?

UserContext.js UserContext.js

import React, {useState, createContext, useEffect} from 'react'
import Firebase from 'firebase'
import { Redirect } from 'react-router'

export const UserContext = createContext();


export const UserProvider = props => {
  const [user, setUser] = useState({
    username: "blank",
    loggendIn: false
  });


  var id = localStorage.getItem('id');
  // check if its null
  console.log(id);
  useEffect(() => {
    if (id != null) {
      console.log('id is there');
      // load user from realtime database
      const dbOBJ = Firebase.database().ref().child("users").child(id);
      dbOBJ.on('value', function(snapshot) {
        setUser(snapshot.val());
      });

    } else {
      console.log('no id :( ');
    }
    console.log(props.history);
    this.props.history.push('/dashboard');
  }, [id]);

  return (
    <UserContext.Provider value = {[user, setUser]} >
    {  props.children}
    </UserContext.Provider>
  );
}

app.js应用程序.js

import React from 'react';
import NavBar from './components/navBar';
import Login from './components/login';
import Session from './components/session';
import Dashboard from './components/dashboard';
import './App.css';
import Container from '@material-ui/core/Container';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';

import { UserProvider } from './model/UserContext'


function App() {

  return (
    <div>
      <UserProvider>
      <Session />
       <NavBar />
        <Container maxWidth="sm">
         <Router>
         <Route path='/Login' component={Login}  />
         <Route path='/Dashboard' component={Dashboard}  />
         </Router>
       </Container>
      </UserProvider>
    </div>
  );
}

export default App;

That is a functional component, there is no instance for this to exist on, history would just be on props .那是一个功能组件,它没有this存在,历史只会在props上。 You also probably need to "inject" the router's history object into props as well.您可能还需要将路由器的历史 object 也“注入”到道具中。

import React, {useState, createContext, useEffect} from 'react'
import Firebase from 'firebase'
import { Redirect, withRouter } from 'react-router'

export const UserContext = createContext();


const UserProvider = ({  // don't export here
  children, // destructuring props here so it is clearer
  history
}) => {
  const [user, setUser] = useState({
    username: "blank",
    loggendIn: false
  });


  var id = localStorage.getItem('id');
  // check if its null
  console.log(id);
  useEffect(() => {
    if (id != null) {
      console.log('id is there');
      // load user from realtime database
      const dbOBJ = Firebase.database().ref().child("users").child(id);
      dbOBJ.on('value', function(snapshot) {
        setUser(snapshot.val());
      });
    } else {
      console.log('no id :( ');
    }
    console.log(props.history);
    history.push('/dashboard'); // <-- no this.props, just props or destructured props
  }, [id]);

  return (
    <UserContext.Provider value = {[user, setUser]} >
    { children }
    </UserContext.Provider>
  );
}

export default withRouter(UserProvider);

I think you're mixing up multiple thing:我认为你混合了多个东西:

Fat arrow functions don't have a this on it defined it'll pick up window as this for your code.胖箭头函数上没有this定义它会为您的代码选择window作为 this 。

 window.name = 'Mamba'; (() => {console.log(this.name)})();

So you need to use the props directly here like this:所以你需要像这样直接在这里使用道具:

this.props.history.push('/dashboard'); => props.history.push('/dashboard'); => props.history.push('/dashboard');

You might like to go through this question if you're still unsuccessful如果您仍然不成功,您可能想通过这个问题go

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React - TypeError:无法读取未定义的属性“道具” - React - TypeError: Cannot read property 'props' of undefined React Redux - Uncaught(in promise)TypeError:无法读取未定义的属性&#39;props&#39; - React Redux - Uncaught (in promise) TypeError: Cannot read property 'props' of undefined 未捕获的TypeError:无法读取react-redux中未定义的属性&#39;props&#39; - Uncaught TypeError: Cannot read property 'props' of undefined in react-redux React TypeError:在传递道具时无法读取未定义的属性“map” - React TypeError: Cannot read property 'map' of undefined on passing props React教程:TypeError:无法读取未定义的属性“ props” - React Tutorial: TypeError: Cannot read property 'props' of undefined TypeError:无法读取undefined的属性'firstName' - 在react中使用'props' - TypeError: Cannot read property 'firstName' of undefined - using 'props' in react React/Redux - TypeError:无法读取未定义的属性“道具” - React/Redux - TypeError: Cannot read property 'props' of undefined 反应功能组件类型错误:无法读取未定义的属性“道具” - React functional component TypeError: Cannot read property 'props' of undefined React Redux - TypeError:无法读取未定义的属性“道具” - React Redux - TypeError: Cannot read property 'props' of undefined 导入函数并使用“ this”获取道具:“ TypeError:无法读取未定义的属性&#39;renderElapsedString&#39;” - Importing function and getting props with “this”: “TypeError: Cannot read property 'renderElapsedString' of undefined”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM