简体   繁体   中英

Is function component that uses React-hook can be render inside from a class component

I use react-hook in my all component. Now when I want to render It's inside React_Router BrowserRouter component It's given me an error.

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

If I understand well your problem, I think you could do nested routes with hoo like it.

Here would be your main router for example:

 import React from 'react'; import {Switch, Route, withRouter, Link} from "react-router-dom"; import MyComponent from "./MyComponent"; class Main extends React.Component { render() { return ( <div className='main'> <Switch> <Route exact path='/test' component={MyComponent} /> </Switch> </div> ); } } export default withRouter(Main);

And Here would be your routed component with nested route.

 import React from 'react'; import {Switch, Route, withRouter} from "react-router-dom"; class MyComponent extends React.Component { render() { const {path} = this.props.match; return ( <div className='test'> <Switch> <Route path={`${path}/catalog`}> <div>Route catalog</div> </Route> <Route exact path={path}> <div>Route dashboard</div> </Route> </Switch> </div> ); } } export default withRouter(MyComponent);

I had the same error in the past days. In my case the problem was that i use render prop of Route component instead of component prop

<Route render={FunCompWithHooks} /> {/* wrong */}
<Route component={FunCompWithHooks} /> {/* correct */}

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