老师您好,代码中为什么会有两次return,HOC返回一个组件,第二个return正好返回了包装的子组件,第一个return必须存在吗?
export const withAddtoChart= (ChildComponet: React.ComponentType) => {
return (props) => {
const setState = useContext(appSetStateContext);
.....
return <ChildComponet {...props} addShoppingChart={addShoppingChart}/>
};
另外如果把代码修改如下:
export const withAddtoChart= (ChildComponet: React.ComponentType) => {
const test= (props) => {
const setState = useContext(appSetStateContext);
…
则会报错,React Hook “useContext” is called in function “test” that is neither a React function component nor a custom React Hook function.
说明React hooks只能用于React函数或者自定义Hook中,那为什么加上return就变成了React函数?
React 18 精讲 + 结合 TS 实战 + 热门业务开发,获取必备技能
了解课程