簡體   English   中英

當 propTypes 驗證失敗時,強制 ReactJS 拋出真正的錯誤?

[英]Force ReactJS to throw real errors when propTypes validation fails?

目前,如果propType驗證失敗,ReactJS 使用console.warn發出警告。 我真的,真的很想在開發模式下出現一個真正的錯誤,所以它可能會使我們的持續集成構建失敗,而不是僅僅打印一條可能在 shuffle 中丟失的消息。

已經對此進行了討論,例如在此功能請求中,並且此相關問題按預期描述了當前行為。 這很好,但我個人希望它拋出一個錯誤。

假設 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 和 propTypes 參數的支持: 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} />;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM