简体   繁体   English

当我在同一路由中传递回调函数时 this.props.history.push() 不起作用

[英]this.props.history.push() is not working when i pass the callback function in same route

I have我有

<Route path='/login' exact render={() => <LoginPage sectionEmailHandler={this.sectionEmailHandler} />} /> 

this Route with path /login ,and i am passing callback function这条带有路径/登录名的路由,我正在传递回调函数

sectionEmailHandler 

and inside login component i am doing在我正在做的登录组件中

this.props.history.push('/dashboard/session')

so now i am ,getting the error that所以现在我得到了错误

TypeError: Cannot read property 'push' of undefined类型错误:无法读取未定义的属性“推送”

but when i did not pass the callback function with /login route like this但是当我没有像这样使用 /login 路由传递回调函数时

<Route path='/login' exact component={LoginPage} /> 

then it works fine.然后它工作正常。

Below is my code下面是我的代码

Pages/index.js页面/index.js

import React, { Component } from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import LoginPage from '../components/Login/LoginPage'
import StartPage from '../components/startPage/StartHere'
import users from '../pages/users/index'

class Home extends Component {

    // constructor(props){
    //     super(props)
    //     this.state={
    //         email:''
    //     }
    // }


    sectionEmailHandler=(email)=>{
       console.log(email)
    }


    render() {
        return (
        <>
      <Router >
   
         <Switch>
            <Route path='/' exact component={StartPage} />
            <Route path='/login' exact render={() => <LoginPage sectionEmailHandler={this.sectionEmailHandler} />} />
            <Route path='/dashboard/session' exact component={users} />
        </Switch>
    </Router>
        </>
    )
}

}

export default Home;

LoginPage.js登录页面.js

import React, { Component } from 'react'
import { Redirect } from 'react-router-dom';
import { Button,Label } from 'reactstrap';
import {Mutation, Query} from 'react-apollo';
import gql from 'graphql-tag'
import LoginPage_logo_img from '../../Assets/LoginPage_logo_img.png'
import LoginPage_email_icon from '../../Assets/LoginPage_email_icon.svg'
import LoginPage_lock_icon from '../../Assets/LoginPage_lock_icon.svg'
import './LoginPage.css'

const AUTH_USER = gql`
  mutation TokenAuth($username: String!,$password : String!) { 
    tokenAuth(username: $username,password : $password) {
       token,
       payload,
       refreshExpiresIn
    }
}
`;


 class LoginPage extends Component {

constructor(props){
    super(props)
    this.state={
        fields: {},
        errors: {},
        email:'',    
        password:''
    }
   
    this.textInputemail = React.createRef();
    this.textInputpassword = React.createRef();
}



handleValidation(){
      
    let fields = this.state.fields;
    let errors = {};
    let formIsValid = true;

    //Email
    if(!fields["email"]){
       formIsValid = false;
       errors["email"] = "Please complete the field above";
    }

    if(typeof fields["email"] !== "undefined"){
       let lastAtPos = fields["email"].lastIndexOf('@');
       let lastDotPos = fields["email"].lastIndexOf('.');

       if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
          formIsValid = false;
          errors["email"] = "Please enter the valid Email";
        }
   }  

   this.setState({errors: errors});
   return formIsValid;
}

handleChnage=()=>{
    let fields = this.state.fields;
   
    fields[this.textInputpassword.current.name] = this.textInputpassword.current.value;        
    fields[this.textInputemail.current.name] = this.textInputemail.current.value;        
        
    this.setState({fields});
}

    render() {
    
        return (
            <Mutation mutation={AUTH_USER}>
               {(authUser,{data})=>(  
                   
            <div className="LoginPage-container">
                <div className="LoginPage-wrapper">
                   <img src={LoginPage_logo_img} alt="" className="LoginPage-logo"/>
                   <div className="LoginPage-email">
                       <img src={LoginPage_email_icon} alt=""/>
                     <input ref={this.textInputemail} type="email" name="email" onChange={this.handleChnage}/>
                  </div>
                  <div className="LoginPage-password">
                      <img src={LoginPage_lock_icon} alt=""/>
                     <input ref={this.textInputpassword} type="password" name="password" placeholder="Password" onChange={this.handleChnage}/>
                  </div>
                <Button className="LoginPage-signIn" onClick={(e)=>{
                    e.preventDefault()

                    const {email,password}= this.state.fields;
                    
              
                    authUser({
                        variables:{
                            username:email,
                            password:password
                        }
                    }).then((res)=>{
                       
                        let token=res.data.tokenAuth.token;
                        localStorage.setItem('WonEToken', token);
                         this.props.sectionEmailHandler(email)
                        console.log(this.props)
                         this.props.router.push('/dashboard/session');
                       
                    }).catch((err)=>{
                        console.log(err+'Error while fetching the user details');
                    })


                }}>Sign In</Button>
                <h2></h2>
                </div>
            </div>
            )}
            </Mutation>
        )
    }
}

export default LoginPage

Pass the route props from the Route on to the rendered component.路由道具Route传递到渲染组件。

<Route
  path='/login'
  exact
  render={(routeProps) => ( // <-- { history, location, match }
    <LoginPage
     sectionEmailHandler={this.sectionEmailHandler}
     {...routeProps} // <-- spread in to component
    />
  )}
/>

I assume you are using react router .我假设您正在使用react router

In your example在你的例子中

<Route path='/login' exact render={() => <LoginPage sectionEmailHandler={this.sectionEmailHandler} />} />

You need to pass in the props like this.你需要像这样传递道具。

<Route path='/login' exact render={(props) => <LoginPage sectionEmailHandler={this.sectionEmailHandler} {...props} />} />

The props contains match, location, history道具包含比赛、地点、历史

The children render prop receives all the same route props as the component and render methods, except when a route fails to match the URL, then match is null.子渲染道具接收与组件和渲染方法相同的所有路由道具,除非路由无法匹配 URL,则 match 为空。

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

相关问题 ReactJs this.props.history.push()不起作用 - ReactJs this.props.history.push() is not working this.props.history.push('/') 在 CLASS 组件中不起作用 - this.props.history.push('/') IS NOT WORKING in CLASS Component this.props.history.push() 在 ReactJS 中不起作用 - this.props.history.push() not working in ReactJS 当我们使用 this.props.history.push(&quot;/next Component&quot;) 移动到下一个组件时,我们可以传递一个值吗? - can we pass a value when we move to next component using this.props.history.push("/next Component")? this.props.history.push刚刚刷新后正在运行 - this.props.history.push is working just after refresh React-router v4 this.props.history.push(...) 不工作 - React-router v4 this.props.history.push(...) not working 在 this.props.history.push 上刷新页面,使用相同的 url - Refresh page on this.props.history.push with same url this.props.history.push 在使用 HOC 记录器时不起作用 - this.props.history.push is not working while using HOC for logger 类型错误:无法使用 this.props.history.push 读取未定义的属性“推送” - TypeError: Cannot read property 'push' of undefined with this.props.history.push this.props.history.push 适用于某些组件而不适用于其他组件 - this.props.history.push works in some components and not others
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM