强制 ReactJS 在 propType 验证失败时抛出真正的错误

Force ReactJS to throw real errors when propTypes validation fails?

本文关键字:错误 ReactJS propType 验证 失败 强制      更新时间:2023-09-26

目前,如果propType验证失败,ReactJS使用console.warn发出警告。我真的,真的想要在开发模式下出现真正的错误,这样它可能会使我们的持续集成构建失败,而不仅仅是打印可能在随机播放中丢失的消息。

已经对此进行了讨论,例如在此功能请求中,并且此相关问题按预期描述了当前行为。这很好,但我个人希望它抛出错误。

假设 ReactJS 不会很快为此提供更好的支持,最好的解决方法是什么?到目前为止,我想出的最好的方法是覆盖测试console.warn,例如

console.warn = function(msg) {
    throw new Error(msg);
};

这样做的缺点是,在测试中实现它可能很棘手,而且它不是特定于 React 的,因此还需要处理其他console.warn调用。

从这个答案中,您可以根据典型的反应消息检查错误消息,并且只抛出这些消息。不完美,但可能离您要查找的内容更近一步:

let warn = console.warn;
console.warn = function(warning) {
  if (/(Invalid prop|Failed propType)/.test(warning)) {
    throw new Error(warning);
  }
  warn.apply(console, arguments);
};

Facebook昨天推出的FlowType听起来正是你所追求的。它可以分析代码、推断类型并在编译时引发错误。

它特别包括对 React 和 propType 参数的支持:https://flow.org/en/docs/react/components/

更新(7 月 21 日)- 上面的链接已修复,但鉴于 Facebook 最近在 Flow 上进行了更改,将内部使用置于未来社区使用之上,因此建议将 TypeScript 用于新项目。例:

https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/class_components/

React 17 - 投入测试

beforeEach(() => {
  const { error } = console;
  jest.spyOn(console, 'error').mockImplementation((...args) => {
    const message = args[0].replace('%s%s', '').replace('%s', args[1]) + args[2];
    if (/(Invalid prop|Failed prop type)/.test(message)) {
      throw new Error(message);
    }
    error.apply(console, args);
  });
});
function TodoProvider(props) {
  const [items, dispatch] = useReducer(todoReducer, initialItems);
  const todoData = { items, dispatch };
  return <TodoContext.Provider value={todoData} {...props} />;
}