React-route useHistory 对我不起作用

问题描述

嗨,我正在做一个带有 react 和 nodejs 的项目,如果有人成功登录并想使用 useHistory 重定向到另一个页面而不更新,我正在使用 window.location.href 重定向到另一个页面,但它没有不工作,它给了我以下错误

Error

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This Could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See -invalid-hook-call for tips about how to debug and fix this problem.

我按原样使用它,因为它在 react-route 文档中(我认为)

代码

import React,{ Component } from 'react'
import './main.css';
import {browserRouter as Router,Switch,Route,Link,Redirect,useHistory,useLocation,browserHistory,withRouter} from 'react-router-dom';

import Register from './components/ComponentRegister'
import Login from './components/ContainerLogin'
import ChatPrincipal from './Chat/ChatPrincipal'

class App extends Component {


  
  state = {
    username: '',status: Number,message: '',messageError: ''
  }

componentDidMount(){
// localStorage.setItem('sesion','')
}

  userLogin = (username,password) =>{
    const url = 'http://192.168.1.7:3000/api/login'


     fetch('/api/register',{
      method: 'POST',headers: {
        'Accept': 'application/json','Content-Type': 'application/json'
      },body: JSON.stringify({username: username,password: password})
    })
    .then(r => r.json())
    .then(data =>{
      if(data.status === 200){
        console.log('hola')
        this.setState({
          status: data.status,message: data.message,username: username
        })
        this.userSearch()
      }
    }) 
    
  }


  login = (username,password) =>{
    let history = useHistory() <====================== Error
    fetch('/api/login',password: password})
    })
    .then(r => r.json())

    .then(data =>{
      console.log(data.status)
      if(data.status === 200){
        console.log('si')
         this.setState({
          status: data.status,username: username
        })
        this.userSearch() 
      }else{
        this.setState({
          messageError: data.message,status: data.status
        })
        console.log('Error')
        const error = document.getElementById('Error')

      }
    }) 
 
    
  }
  

  userSearch = () =>{
    console.log('hola')
    const sesionGet = localStorage.getItem('sesion')
    const url = `/api/userSearch/${this.state.username}`
    fetch(url)
    .then(r => r.json())
    .then(data => {
      console.log(data.user._id)
        localStorage.setItem('sesion',data.user._id)
    })
    .then(console.log)
    setTimeout(() => {
      window.location.href = "/"
    },1000);
  }

  userRegister = (username,password) =>{
    const url = ''
    
    fetch('/api/register',password: password})
    })
    .then(r => r.json())
    .then(data => {
      if(data.status === 200){
        console.log(data.status,'jeje')
        this.setState({
          status: data.status
        })
      }else{
        this.setState({
          status: data.status,messageError: data.message

        })
      }
    })
  }

  render() {
    return (

      
     <Router>
      <div>
          <Switch>

          <Route exact path="/">
          <ChatPrincipal/>
          </Route>

          <Route exact path="/init/login">
          <Login status={this.state.status} error={this.state.messageError} login={this.login}/>
          </Route>

          <Route exact path="/init/register">
          <Register status={this.state.status} register={this.userRegister}/>
          </Route>

          <Route exact path="/init/chat">
          
          </Route >
          </Switch>

        
      </div>
      </Router> 
    )
  }
}


export default App;
)

并且立即调用 useHistory 函数会给我上述错误,导致我无法使用您的函数重定向页面

history.push('/')

解决方法

您应该在组件内使用钩子。 push 方法也将具有 pathname 属性的对象作为参数:history.push({pathname: '/'})。官网Hook的另一个使用规则:Rules of Hooks

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...