簡體   English   中英

使用 React-hook 的 function 組件是否可以從 class 組件內部渲染

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

我在我的所有組件中使用 react-hook。 現在,當我要渲染它時,它在 React_Router BrowserRouter 組件內,它給了我一個錯誤。

錯誤按摩:無效的掛鈎呼叫。 鈎子只能在 function 組件的主體內部調用

如果我能很好地理解你的問題,我認為你可以用 hoo 做嵌套路由。

例如,這將是您的主路由器:

 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);

這將是您的帶有嵌套路由的路由組件。

 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);

在過去的幾天里,我遇到了同樣的錯誤。 在我的情況下,問題是我使用 Route 組件的渲染道具而不是組件道具

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM