Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs react重定向中的问题,如何使用history.push_Reactjs_Redirect_React Router - Fatal编程技术网

Reactjs react重定向中的问题,如何使用history.push

Reactjs react重定向中的问题,如何使用history.push,reactjs,redirect,react-router,Reactjs,Redirect,React Router,当满足特定条件时,我很难将反应路径重定向到其他路径,我发现解决方案是useHistory,但我不能/我不能在我的类组件中使用它 我该怎么做呢 import React,{useState,useContext,Component} from 'react' import Navbar from '../../shared/components/navigation/Navbar'; import {AuthContext} from '../../shared/context/auth-cont

当满足特定条件时,我很难将反应路径重定向到其他路径,我发现解决方案是useHistory,但我不能/我不能在我的类组件中使用它 我该怎么做呢

import React,{useState,useContext,Component} from 'react'
import Navbar from '../../shared/components/navigation/Navbar';
import {AuthContext} from '../../shared/context/auth-context'
import { BrowserRouter, Route, Redirect} from 'react-router-dom'
import PropTypes from 'prop-types'

export default class Auth extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isLogin : true,
            name:'',
            email:'',
            password:''
        };
      }
    
    render() {

        const authSubmitHandler = async event=>{
            event.preventDefault();
            // AuthContext.login();
            const data = new FormData(event.target);

            if(this.state.isLogin){
                try{
                    console.log(data)
                   const response = await fetch('http://localhost:5000/api/users/login',{
                        method:'POST',
                        headers:{
                            'Content-Type': 'application/json'
                        },
                        body:JSON.stringify({
                            email: data.get('email'),
                            password: data.get('password')
                          })
                    });
                        const responseData = await response.json();
                        console.log(responseData);
    
                        if(response.ok){
                            return <Redirect to='/' />
                        }
                }
                catch(err){
                    console.log(err);
    
                } 
            }
            else{
            try{
                console.log(data)
               const response = await fetch('http://localhost:5000/api/users/signup',{
                    method:'POST',
                    headers:{
                        'Content-Type': 'application/json'
                    },
                    body:JSON.stringify({
                        name: data.get('name'),
                        email: data.get('email'),
                        password: data.get('password')
                      })
                });
                    const responseData = await response.json();
                    console.log(responseData);

                    if(response.ok){
                        return <Redirect to='/' />
                    }
            }
            catch(err){
                console.log(err);

            } 
        }
    }

        const switchModeHandler = (event)=>{
            this.setState({isLogin:!this.state.isLogin})
            // this.state.isLogin =!this.state.isLogin;
        }


        return (
        <React.Fragment>
            <Navbar/>
        <div>
            <form onSubmit={authSubmitHandler}>

                {!this.state.isLogin &&
                <label>
                username
                <input name="name" type="text" id="name" label="your name"/>
                </label>
                }

                email
                <input type="email" name="email" id="email" label="email" />

                password
                <input  name="password" type="password" id="password" label="password" />

                <button type="submit">submit</button>
            </form>
            <button onClick={switchModeHandler}>switch to {this.state.isLogin?'SIGNUP':"LOGIN"}</button>
        </div>
        </React.Fragment>
        )
    }
}

import React,{useState,useContext,Component}来自“React”
从“../../shared/components/navigation/Navbar”导入导航栏;
从“../../shared/context/auth context”导入{AuthContext}
从“react router dom”导入{BrowserRouter,Route,Redirect}
从“道具类型”导入道具类型
导出默认类Auth扩展组件{
建造师(道具){
超级(道具);
此.state={
伊斯洛金:是的,
名称:“”,
电子邮件:“”,
密码:“”
};
}
render(){
const authSubmitHandler=异步事件=>{
event.preventDefault();
//AuthContext.login();
const data=新表单数据(event.target);
if(this.state.isLogin){
试一试{
console.log(数据)
const response=等待获取('http://localhost:5000/api/users/login',{
方法:'POST',
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify({
email:data.get('email'),
密码:data.get('password')
})
});
const responseData=await response.json();
控制台日志(responseData);
if(response.ok){
返回
}
}
捕捉(错误){
控制台日志(err);
} 
}
否则{
试一试{
console.log(数据)
const response=等待获取('http://localhost:5000/api/users/signup',{
方法:'POST',
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify({
name:data.get('name'),
email:data.get('email'),
密码:data.get('password')
})
});
const responseData=await response.json();
控制台日志(responseData);
if(response.ok){
返回
}
}
捕捉(错误){
控制台日志(err);
} 
}
}
常量switchModeHandler=(事件)=>{
this.setState({isLogin:!this.state.isLogin})
//this.state.isLogin=!this.state.isLogin;
}
返回(
{!this.state.isLogin&&
用户名
}
电子邮件
密码
提交
切换到{this.state.isLogin?'SIGNUP':“LOGIN”}
)
}
}
在这里,这是我想用来重定向的部分,当我在auth表单上按submit时,目前没有发生任何事情

if(response.ok){
   return <Redirect to='/' />
}
if(response.ok){
返回
}

我想在您的组件中更改很多内容,但要回答您的具体问题,您需要的不是
useHistory
。这是一个钩子,您可以在不编写类组件的情况下使用它。在您的情况下,您应该使用的是
with router
,这是一个可以为您提供所需的道具
历史记录的HoC

删除第一行中的导出默认值,添加以下导入

从“反应路由器”导入{withRouter}

然后像这样使用HoC:

使用路由器导出默认值(Auth)

然后,您将能够访问历史道具,使用它可以调用push并在方法中更改路由


我会查看react router的文档以了解更多详细信息

我会在您的组件中更改很多内容,但要回答您的具体问题,您需要的不是
useHistory
。这是一个钩子,您可以在不编写类组件的情况下使用它。在您的情况下,您应该使用的是
with router
,这是一个可以为您提供所需的道具
历史记录的HoC

删除第一行中的导出默认值,添加以下导入

从“反应路由器”导入{withRouter}

然后像这样使用HoC:

使用路由器导出默认值(Auth)

然后,您将能够访问历史道具,使用它可以调用push并在方法中更改路由

我会查看react router的文档以了解更多详细信息