📌  相关文章
📜  typeerror object(...) is not a function react useParams - Javascript (1)

📅  最后修改于: 2023-12-03 15:35:23.654000             🧑  作者: Mango

TypeError: object(...) is not a function for React useParams()

In React, the useParams() hook allows you to access the parameters of a dynamic route that was defined using React Router. This can be extremely helpful when working on dynamic applications. However, if you encounter the error TypeError: object(...) is not a function while using useParams(), there are a few things you can check to resolve the issue.

Common Causes and Solutions for the Error
  • Using the wrong version of React Router.

    If you're using an older version of React Router, it's possible that the useParams() hook doesn't exist. Make sure you're using the latest version of React Router (currently v5) and that you've imported it properly:

    import { useParams } from 'react-router-dom';
    
  • Not wrapping your components in a <Router> or <BrowserRouter> component.

    If you haven't wrapped your components in a routing component, useParams() won't work. Make sure that you're wrapping your App component (or any other component that uses useParams()) in a <Router> or <BrowserRouter> component in the index.js file:

    import { BrowserRouter as Router } from 'react-router-dom';
    
    ReactDOM.render(
      <Router>
        <App />
      </Router>,
      document.getElementById('root')
    );
    
  • Using useParams() outside of a routing context.

    If you're not using useParams() inside a component that is rendered as a Route component, it won't work. Double-check that the component using useParams() is rendered inside a Route component:

    import { Route } from 'react-router-dom';
    
    function MyComponent() {
      const { parameter } = useParams();
      // ...
    }
    
    function App() {
      return (
        <div>
          <Route path="/:parameter" component={MyComponent} />
        </div>
      );
    }
    

    Also note that the parameter names in the route and in the useParams() hook should match exactly, including case.

  • Using a callback function in setState() instead of an object.

    If you're using setState() to update the state of a component that is using useParams(), make sure that you're passing an object to setState(), not a callback function:

    // Bad: using a callback function in setState()
    const { parameter } = this.props.match.params;
    this.setState(state => ({ parameter: state.parameter + parameter }));
    
    // Good: passing an object to setState()
    const { parameter } = this.props.match.params;
    this.setState({ parameter: this.state.parameter + parameter });
    

By double-checking the above potential causes, you should be able to resolve the TypeError: object(...) is not a function error when using useParams() in your React application.