reactjs - react 使用历史: Hooks can only be called inside the body of a function component

标签 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

我正在尝试使用“react-router”中的useHistory。但是,似乎我一直收到此错误。 尽管我尝试在线寻找解决方案,但我的错误看起来不像“打破钩子(Hook)规则”或任何其他错误。

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

我也添加了我的 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;

最佳答案

您正在从react-router导入useHistory,但这是react-router-dom的一个函数,所以尝试像这样导入

import { useHistory } from "react-router-dom";

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

关于reactjs - react 使用历史: Hooks can only be called inside the body of a function component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61113602/

相关文章:

javascript - React 和 ReactDOM 未定义但已安装

reactjs - 如何在React中实现进度条?

javascript - 优化 React 应用程序 - 仅根据 React [React.JS]

javascript - react 组件 Prop 中的流泛型

typescript - 如何解决 react native 屏幕 typescript 中未定义的route.params

javascript - React/Redux - 从 Url ID 获取详细信息

reactjs - react NotFoundError : Failed to execute 'insertBefore' on 'Node' : The node before which the new node is to be inserted is not a child of this node

javascript - Router 6 - 从父组件调用子组件函数

reactjs - 如何使用 React Router 在 React 中正确同步 useEffect 和 useLocation Hook ?

reactjs - 在 React Router 中使用参数重定向到父路由