简体   繁体   中英

React Router: Invalid hook call. Hooks can only be called inside of the body of a function component

I have a normal react app, using react router. When trying to get the url params in Box.js, I get this error: Invalid hook call. Hooks can only be called inside of the body of a function component. This is the code:

Box.js

import React from 'react'
import { useParams } from "react-router-dom";

function Box()
{
    let params = useParams();
    return (
        <div>
            <h1>{params}</h1>
        </div>
    )
}
export default Box();

App.js

import
{
  Routes,
  Route
} from "react-router-dom";
import Box from './Box';
function App()
{
  return (
    <div className="App">
      <Routes>
        <Route exact path="/palette/:id/:color" element={<Box />} />
      </Routes>
    </div>
  );
}

export default App;

You should not call a function while exporting.

import React from 'react'
import { useParams } from "react-router-dom";

function Box()
{
    let params = useParams();
    return (
        <div>
            <h1>{params}</h1>
        </div>
    )
}
export default Box;

Remove the () from the export part

import React from 'react'
import { useParams } from "react-router-dom";

function Box(){
    let params = useParams();
    return (
        <div>
            <h1>{params}</h1>
        </div>
    )
}
export default Box;

If you are using npm link or any other library, your bundler might see two different reacts and show that error see here

or you can remove the ()

import React from 'react'
import { useParams } from "react-router-dom";

function Box()
{
    let params = useParams();
    return (
        <div>
            <h1>{params}</h1>
        </div>
    )
}
export default Box();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM