React-route useHistory 对我不起作用

时间:2021-01-30 16:56:03

标签: javascript reactjs npm frontend react-router-v4

嗨,我正在做一个带有 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', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({username: username, password: password})
    })
    .then(r => r.json())

    .then(data =>{
      console.log(data.status)
      if(data.status === 200){
        console.log('si')
         this.setState({
          status: data.status,
          message: data.message,
          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', {
      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(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('/')

1 个答案:

答案 0 :(得分:0)

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