【问题标题】:How to redirect in React on click?如何在点击时在 React 中重定向?
【发布时间】:2021-03-24 15:21:28
【问题描述】:

在我的 react 应用程序中,我使用 useHistory 挂钩重定向到我的 Home 组件。为什么 useHistory 未定义,我将如何解决这个问题?

App.js

import 'bootstrap/dist/css/bootstrap.css' 
import React from "react";
import { Button } from 'react-bootstrap';
import { BrowserRouter, Route, useHistory} from 'react-router-dom';

import { Switch } from 'react-router-dom/cjs/react-router-dom.min';
import './App.css';
import Home from './components/Home/Home';



const App = () =>
{
  const history = useHistory()
  const handleClick = () => 
  {
    console.log(history)
    console.log("handle click")
    // history.push("/home") this line throws "cannot read property of undefined" error
  }

    return (
      <>
        <BrowserRouter>
          <Button onClick = {handleClick} variant = "primary">Get Started</Button>
  
          <Switch>
            <Route path="/home" exact component = {Home}/>
          </Switch>
        </BrowserRouter>
  
      </>
    );      
}

export default App;

【问题讨论】:

标签: javascript node.js reactjs


【解决方案1】:

尝试在此组件之外使用useHistory() 并查看它是否有效。看来您是在路由器本身之前调用该函数,并且两者都是从 react-router-dom 导入的。

【讨论】:

    猜你喜欢
    • 2013-08-15
    • 2020-03-11
    • 2016-12-22
    • 2018-12-17
    • 1970-01-01
    • 2018-03-22
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多