将 hoist-non-react-statics 与 withRouter 一起使用
Use hoist-non-react-statics with withRouter
如何将 hoist-non-react-statics
与 withRouter
一起使用
我正在 Feedback
组件中添加一个静态方法。
这是我的原始代码。我正在尝试使用 Context API (react v 16.6)
中的新更改
Feedback.contextType = AppContext;
export default withRouter( Feedback );
这工作正常,但我在控制台中收到以下警告。
Warning: withRouter(Feedback): Function components do not support
contextType.
所以为了修复警告,我使用了 Dan here. Its also mentioned in react docs
提出的方法
所以我现在有这段代码,但它不起作用。
导入了hoist-non-react-statics
import {Link, withRouter} from 'react-router-dom';
import hoistNonReactStatics from 'hoist-non-react-statics';
并像这样导出组件
Feedback.contextType = AppContext;
hoistNonReactStatics( Feedback, withRouter(Feedback) );
export default Feedback;
但由于某些原因,props
中未填充路由器信息(历史、比赛等)
为什么它不起作用的任何指示?
第二个片段不应该工作,因为 withRouter(Feedback)
没有从模块中导出。
正如 linked issue 所解释的,问题是 hoist-non-react-statics
没有被正确处理 contextType
static 属性。这已在最新的 hoist-non-react-statics
版本中修复。由于 react-router
使用旧的 hoist-non-react-statics
版本作为依赖项,这可以就地修复:
Feedback.contextType = AppContext;
export default Object.assign(withRouter(Feedback), { contextType: undefined });
或:
Feedback.contextType = AppContext;
const FeedbackWithRouter = withRouter(Feedback);
delete FeedbackWithRouter.contextType;
export default FeedbackWithRouter;
或:
export default withRouter(Feedback);
Feedback.contextType = AppContext;
我在使用和不使用 'hoist-non-react-statics' 时都收到了警告,当我将 react-router-dom 更新到最新版本 (5.0.0)
时,它消失了
如何将 hoist-non-react-statics
与 withRouter
我正在 Feedback
组件中添加一个静态方法。
这是我的原始代码。我正在尝试使用 Context API (react v 16.6)
中的新更改Feedback.contextType = AppContext;
export default withRouter( Feedback );
这工作正常,但我在控制台中收到以下警告。
Warning: withRouter(Feedback): Function components do not support contextType.
所以为了修复警告,我使用了 Dan here. Its also mentioned in react docs
提出的方法所以我现在有这段代码,但它不起作用。
导入了hoist-non-react-statics
import {Link, withRouter} from 'react-router-dom';
import hoistNonReactStatics from 'hoist-non-react-statics';
并像这样导出组件
Feedback.contextType = AppContext;
hoistNonReactStatics( Feedback, withRouter(Feedback) );
export default Feedback;
但由于某些原因,props
为什么它不起作用的任何指示?
第二个片段不应该工作,因为 withRouter(Feedback)
没有从模块中导出。
正如 linked issue 所解释的,问题是 hoist-non-react-statics
没有被正确处理 contextType
static 属性。这已在最新的 hoist-non-react-statics
版本中修复。由于 react-router
使用旧的 hoist-non-react-statics
版本作为依赖项,这可以就地修复:
Feedback.contextType = AppContext;
export default Object.assign(withRouter(Feedback), { contextType: undefined });
或:
Feedback.contextType = AppContext;
const FeedbackWithRouter = withRouter(Feedback);
delete FeedbackWithRouter.contextType;
export default FeedbackWithRouter;
或:
export default withRouter(Feedback);
Feedback.contextType = AppContext;
我在使用和不使用 'hoist-non-react-statics' 时都收到了警告,当我将 react-router-dom 更新到最新版本 (5.0.0)
时,它消失了