[英]React - useCallback throwing error on renderProps function
I'm passing renderProps function in the props.我正在道具中传递 renderProps 函数。 i want to wrap it with useCallback, so the optimised child component will no re-render on the function creation.我想用 useCallback 包装它,所以优化的子组件不会在函数创建时重新渲染。
when wrapping the function with useCallback i get this error:使用 useCallback 包装函数时,出现此错误:
Invalid hook call.无效的钩子调用。 Hooks can only be called inside of the body of a function component.钩子只能在函数组件的主体内部调用。 This could happen for one of the following reasons:这可能是由于以下原因之一造成的:
- You might have mismatching versions of React and the renderer (such as React DOM)你可能有不匹配的 React 版本和渲染器(例如 React DOM)
- You might be breaking the Rules of Hooks你可能会违反 Hooks 规则
- You might have more than one copy of React in the same app您可能在同一个应用程序中拥有多个 React 副本
none of the above applies to my situation.以上都不适用于我的情况。
renderCell = React.useCallback((
{
events,
popperPlacement,
popperStyle,
time
}
) => {
const { localeToggle } = this.state;
const { weekStarter, isTimeShown } = this.props;
const eventsListPopperStyle = utils.isWeekFirst(time, weekStarter) ||
utils.isWeekSecond(time, weekStarter) ? { left: '-17% !important' } : { left: '17% !important' };
return (
<MonthlyCell
events={events}
isTimeShown={isTimeShown}
popperPlacement={popperPlacement}
popperStyle={popperStyle}
time={time}
eventsListPopperStyle={eventsListPopperStyle}
/>
)
}, [])
Because hooks doesn't work inside class components, the error was thrown.因为钩子在类组件内不起作用,所以抛出了错误。 I managed to find a work around by providing the second parameter for the React.memo.通过为 React.memo 提供第二个参数,我设法找到了解决方法。 in the function i provided, i compare the prevProps and nextProps, and when the prop is a function i disregard it and return true.在我提供的函数中,我比较了 prevProps 和 nextProps,当 prop 是一个函数时,我会忽略它并返回 true。 it might not work for everyone because sometime the function do change, but for situations when it's not, it's ok.它可能并不适用于所有人,因为有时功能确实会发生变化,但对于不发生变化的情况,也没关系。
const equalizers = {
object: (prevProp, nextProp) => JSON.stringify(prevProp) === JSON.stringify(nextProp),
function: () => true, // disregarding function type props
string: (prevProp, nextProp) => prevProp === nextProp,
boolean: (prevProp, nextProp) => prevProp === nextProp,
number: (prevProp, nextProp) => prevProp === nextProp,
}
export const areEqualProps = (prevProps, nextProps) => {
for (const prop in prevProps) {
const prevValue = prevProps[prop];
const nextValue = nextProps[prop];
if (!equalizers[typeof prevValue](prevValue, nextValue)) { return false; }
}
return true
}
export default React.memo(MyComponent, areEqualProps)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.