微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React-route useHistory 对我不起作用

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。