使用hoist-non-react-statics和withRouter

pha*_*der 5 javascript router reactjs react-router-v4

如何使用hoist-non-react-staticswithRouter

我在Feedback组件中添加静态方法.

这是我的原始代码.我正在尝试使用Context API中的新更改(反应第16.6节)

Feedback.contextType = AppContext;

export default withRouter( Feedback );
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我在控制台中收到以下警告.

警告:withRouter(反馈):功能组件不支持contextType.

所以为了修复警告我在这里使用了Dan提出的方法.它也在反应文档中提到过

所以我现在有了这个代码无效.

进口了 hoist-non-react-statics

import {Link, withRouter} from 'react-router-dom';
import hoistNonReactStatics from 'hoist-non-react-statics';
Run Code Online (Sandbox Code Playgroud)

并导出这样的组件

Feedback.contextType = AppContext;
hoistNonReactStatics( Feedback, withRouter(Feedback) );

export default Feedback;
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,路径信息(历史,匹配等)未填充 props

任何指针为什么它不工作?

Est*_*ask 9

第二个片段不应该工作,因为withRouter(Feedback)不从模块导出.

正如链接问题所解释的那样,问题hoist-non-react-statics是没有contextType正确处理静态属性.这已在最新hoist-non-react-statics版本中修复.由于react-router使用旧hoist-non-react-statics版本作为依赖项,因此可以就地修复:

Feedback.contextType = AppContext;

export default Object.assign(withRouter(Feedback), { contextType: undefined });
Run Code Online (Sandbox Code Playgroud)

要么:

Feedback.contextType = AppContext;

const FeedbackWithRouter = withRouter(Feedback);
delete FeedbackWithRouter.contextType;
export default FeedbackWithRouter;
Run Code Online (Sandbox Code Playgroud)

要么:

export default withRouter(Feedback);

Feedback.contextType = AppContext;
Run Code Online (Sandbox Code Playgroud)