我有一個使用另一個組件作為渲染器的組件。但是,React 不允許我在渲染器組件中使用鉤子,因為它會引發以下錯誤:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
這是我的顯示組件中的一個示例,它是一個錯誤邊界:
class DisplayComponent extends Component {
// ...
render() {
const { rendererComponent } = this.props;
return rendererComponent({ enabled: true, name: 'hello-world' })
}
}
正如你所看到的,rendererComponent在道具DisplayComponent被稱為一個函式,雖然它的一個組成部分,我通過一些道具成其為我這樣呼叫它。
現在,在我使用 的另一個檔案中DisplayComponent,它看起來像這樣:
const RendererComponent = (props) => {
const { enabled, name } = props;
const [testState, setTestState] = useState(); // Error: Invalid hook call
useEffect(() => {
// Error: Invalid hook call
}, [testState]);
return (
<div>{name} - {enabled}</div>
)
}
const App = () => {
return (
<DisplayComponent rendererComponent={RendererComponent} />
)
}
這是關鍵。出于某種原因,我不能用鉤子等useEffect,useState在等RendererComponent。如果我使用它,React 會拋出我上面提到的鉤子無效的錯誤。但我想有一些邏輯需要在RendererComponent.
我如何使用鉤子在組件中以我的方式呼叫狀態和效果?
uj5u.com熱心網友回復:
您正在進行函式呼叫而不是安裝組件,這是兩個不同的呼叫和語法,將其更改為:
class DisplayComponent extends Component {
render() {
// Custom component must be Capitalized
const { rendererComponent: RenderedComponent } = this.props;
return <RenderedComponent enabled name="hello-world" />;
}
}
// Notice that the JSX is transpiled to
React.createElement(RenderedComponent, {
enabled: true,
name: "hello-world"
});
在 React 中,你只能通過呼叫它的 API 來掛載一個組件React.createElement(JSX 是它的糖語法),而一個簡單的函式呼叫是純 JS,它不會觸發 React API,即不會將組件注冊到組件樹。因此像鉤子這樣的內部實作沒有意義,你將在每次渲染時丟失狀態(不會觸發協調)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/381486.html
標籤:javascript 反应 反应钩子
下一篇:CSS類樣式在系結后沒有更新
