在嵌套函数中使用钩子
Using hooks in nested functions
我正在尝试将 React class 组件重写为基于挂钩的功能组件,但我不知道该怎么做。组件逻辑和 JSX 看起来像这样:
export class LeftPanel extends React.Component<ILeftPanelProps, ILeftPanelState> {
const [menuItemsFullList, setMenuItemsFullList] = useState([{links: []}] as any[]);
useEffect(() => {
const { links } = props;
setMenuItemsFullList(links);
}, props.links);
....
return (<>
<SearchBox
onChange={_onSearch}
onClear={_onClearSearchBox}
/>
<NavList
listEntries={[menuItems]}
/>
</>)
我正在重写的函数是 onClearSearchBox:
private _onClearSearchBox() {
this.setState({ menuItems: { ...this.state.menuItemsFullList } });
}
我天真地尝试使用将 setState 变成这样的钩子重写它:
function onClearSearchBox() {
useEffect(() => setMenuItems(menuItemsFullList));
}
这不起作用,我不知道如何重构代码,因为我无法在非 React 组件函数中调用挂钩。将其作为内部函数移动到 React 组件函数中也不起作用。
我收到的错误消息是:
Uncaught Invariant Violation: Invalid hook call. Hooks can only be
called inside of the body of a function component...
我相信我的心态仍然停留在基于 class 的结构上,因为我不知道我将如何着手重构 LeftPanel。我应该如何重构 _onClearSearchBox 以使其与挂钩一起使用?
useEffect 是错误的钩子,来自文档:
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount
, componentDidUpdate
, and componentWillUnmount
combined.
在您的示例中,您需要控制何时调用代码,例如单击按钮。我会说 useCallback 是最合适的钩子:
const onClearSearchbox = useCallback(() => {
setMenuItemsFullList(props.items);
}, [props.items]);
...
<SearchBox onClear={onClearSearchBox} ... />
我正在尝试将 React class 组件重写为基于挂钩的功能组件,但我不知道该怎么做。组件逻辑和 JSX 看起来像这样:
export class LeftPanel extends React.Component<ILeftPanelProps, ILeftPanelState> {
const [menuItemsFullList, setMenuItemsFullList] = useState([{links: []}] as any[]);
useEffect(() => {
const { links } = props;
setMenuItemsFullList(links);
}, props.links);
....
return (<>
<SearchBox
onChange={_onSearch}
onClear={_onClearSearchBox}
/>
<NavList
listEntries={[menuItems]}
/>
</>)
我正在重写的函数是 onClearSearchBox:
private _onClearSearchBox() {
this.setState({ menuItems: { ...this.state.menuItemsFullList } });
}
我天真地尝试使用将 setState 变成这样的钩子重写它:
function onClearSearchBox() {
useEffect(() => setMenuItems(menuItemsFullList));
}
这不起作用,我不知道如何重构代码,因为我无法在非 React 组件函数中调用挂钩。将其作为内部函数移动到 React 组件函数中也不起作用。
我收到的错误消息是:
Uncaught Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component...
我相信我的心态仍然停留在基于 class 的结构上,因为我不知道我将如何着手重构 LeftPanel。我应该如何重构 _onClearSearchBox 以使其与挂钩一起使用?
useEffect 是错误的钩子,来自文档:
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
combined.
在您的示例中,您需要控制何时调用代码,例如单击按钮。我会说 useCallback 是最合适的钩子:
const onClearSearchbox = useCallback(() => {
setMenuItemsFullList(props.items);
}, [props.items]);
...
<SearchBox onClear={onClearSearchBox} ... />