React useHistory:只能在函数组件的主体内部调用挂钩

时间:2020-04-09 03:43:31

标签: reactjs react-router

import 'bootstrap/dist/css/bootstrap.min.css';
import React, {Component}from 'react';
import {BrowserRouter, Route, Link} from 'react-router-dom';
import './App.css';

import {Home} from './Home';
import {About} from './About';
import {List} from './List';
import {Button} from 'reactstrap';

const App = () => {
  return(
  <BrowserRouter className = 'App'>
  
  <h1 className = 'App-header'>Welcome to To Do List</h1>

    <div>
      <ul>
        <>
        <Button outline color="secondary" size="sm" block><Link to='/' style={{color: 'black'}} >Home</Link></Button>{' '}
        <Button outline color="info" size="sm" block><Link to='/about' style={{color: 'black'}} >How to use</Link></Button>
        <Button outline color="success" size="sm" block><Link to='/friends'style={{color: 'black'}}>To do list</Link></Button>
        </>
      </ul>

      <hr/>

      <Route exact path = '/' component={Home} />
      <Route path = '/about' component={About} />
      <Route path = '/friends' component={List} />
      
    </div>
  </BrowserRouter>
  )
}



export default App

我正在尝试从“反应路由器”使用useHistory。但是,似乎我不断收到此错误。 即使我尝试在线查找解决方案,但我的错误似乎不像“突破规则”和其他任何错误。

有什么办法可以解决这个问题?

我也添加了App.js

谢谢

import React from 'react';
import './App.css';
import { useHistory } from 'react-router';
import {Button} from 'reactstrap';

const List = () => {

    const history = useHistory({});

    const handleOnClickLogin = () => {
        alert('login clicked');
        history.push('/');
      };

    return(
        <div className="list-component">
            <h2>To do list</h2>
            <Button color = "primary"
                    onClick={handleOnClickLogin}>
                Add
            </Button>
        </div>
    )
}

export default List;

2 个答案:

答案 0 :(得分:3)

您正在从react-router导入useHistory,但这是来自react-router-dom的功能,因此请尝试像

一样进行导入
import { useHistory } from "react-router-dom";

如果您的package.json文件中不存在此软件包,则当然需要安装此软件包。让我知道它是否有效。

答案 1 :(得分:-1)

如果无法从“ react-router-dom”导入,请尝试运行npm install

$ npm install --save react-router-dom