【问题标题】:useHistory hook is not working although console doesn't show errors尽管控制台没有显示错误,但 useHistory 钩子不起作用
【发布时间】:2021-04-05 03:55:30
【问题描述】:

我正在尝试在 Firebase 注册完成后导航到另一个页面,因此我尝试在注册成功后使用 useHistory 挂钩导航到下一页 注册成功但钩子不起作用,控制台没有显示任何错误

如果钩子在这种情况下不起作用,如果注册成功,我如何导航到下一页?

    import {useHistory} from 'react-router-dom'
const history = useHistory();
      function signup(event) {
        console.log({email, password});
        
        firebase.auth().createUserWithEmailAndPassword(email, password)
          .then((user) => {
            // Signed in 
            // ...
            
            this.history.push('/Quiz')
            console.log(email, password)
            
            firebase.database().ref('users/' + user.uid).set({ email: user.email, password: user.password });
           
          })
          .catch((error) => {
            var errorCode = error.code;
            var errorMessage = error.message;
            // ..
            console.log(errorMessage)
            
          });
          
      }

【问题讨论】:

  • 使用history.push('/Quiz')而不是this.history.push('/Quiz')
  • 也没用
  • 它给出了错误“react hooks can't be used inside callbacks”
  • 检查this answer,这可能会有所帮助
  • 试试console.log(error.message)

标签: reactjs firebase react-router react-hooks react-functional-component


【解决方案1】:

你可以这样做

app.js

import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import Routes from './routes'
const history = createBrowserHistory();

ReactDOM.render(<Router history={history}><Routes/></Router>, node);

signup.js

      import {useHistory} from 'react-router-dom'
      const AppName = () => {
      const history = useHistory();

      function signup(event) {
        console.log({email, password});
        
        firebase.auth().createUserWithEmailAndPassword(email, password)
          .then((user) => {
            // Signed in 
            // ...
            
            history.push('/Quiz')
            console.log(email, password)
            
            firebase.database().ref('users/' + user.uid).set({ email: user.email, password: user.password });
           
          })
          .catch((error) => {
            var errorCode = error.code;
            var errorMessage = error.message;
            // ..
            console.log(errorMessage)
            
          });
          
      }
    return (...)
}

【讨论】:

  • 我已经导入了,但没有在帖子中包含它
  • 删除它并没有帮助
  • 你已经在package.json中打包了history,如果你还没有安装package history,请安装npm install history
  • 什么是包历史?我安装了 react-router-dom
  • 因为使用useHistory,它需要历史才能工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 2015-04-27
相关资源
最近更新 更多