如何隐藏componentWillMount警告

时间:2019-09-12 10:04:58

标签: javascript reactjs

我收到四个不能在控制台中最小化的大警告。这些警告来自我的理解,不是因为我做错了什么,而是因为react-router-dom和react-select使用了不赞成使用的componentWillMount函数。如何摆脱警告?

我尝试在此站点上查找问题,但最接近我发现的解决方案的是https://stackoverflow.com/a/49166225/12057512。由于答案是一年多以前的,所以我想知道是否仍然如此。从那时起,这些大型/受欢迎的npm软件包是否仍未更新?

这是我收到的警告之一(其他类似):

  

react-dom.development.js:11494警告:componentWillMount已被执行   重命名,不建议使用。参见https:// fb。   我/ react-async-component-lifecycle-hooks了解详情。

     
      
  • 将具有副作用的代码移动到componentDidMount,并在构造函数中设置初始状态。
  •   
  • 将componentWillMount重命名为UNSAFE_componentWillMount以在非严格模式下禁止显示此警告。在React 17.x中,只有UNSAFE_名称   将工作。要将所有已弃用的生命周期重命名为其新名称,您可以   可以在您的项目中运行npx react-codemod rename-unsafe-lifecycles   源文件夹。
  •   
     

请更新以下组件:BrowserRouter,Route,Router,   切换

(我实际上尝试运行“ npx react-codemod named-unsafe-lifecycles”,但没有区别)

我无法控制这些npm软件包在内部的工作方式,因此感到沮丧的是,我不断收到这些无法修复或删除的警告。

5 个答案:

答案 0 :(得分:4)

解决此问题的常用方法是更新受影响的库(正如您所说的react-router和react-select)。如果这些内容得以维护,则它们将发布不会产生这些警告的新版本。如果那不是您的选择,那么我不知道,我认为React无法抑制特定的警告。

请注意,警告仅显示在React的开发版本中,而不会显示在React的生产版本中(请参见DOCs)。

答案 1 :(得分:3)

我找到的最好的..

const warn = console.warn;
export function logWarning(...warnings: ){
  let showWarning = true;
  warnings.forEach(warning => {
    if     (warning.includes("UNSAFE_"))    showWarning = false;
    else if(warning.includes("SourceMap"))  showWarning = false;
    else if(warning.includes("DevTools"))   showWarning = false;
  });
  if(showWarning) warn(...warnings);
}


console.warn  = logWarning;

答案 2 :(得分:1)

使用以下代码:

console.disableYellowBox = true;

答案 3 :(得分:0)

JeanMGirard 的回答在某些情况下会导致 Uncaught RangeError: Maximum call stack size exceeded,例如当您忘记将依赖项添加到 useEffect React Hook 内的依赖项数组时。这会使调试代码中的某些错误变得非常困难。

通常,React DevTools 会通过显示警告原因和可能的解决方案来处理此问题。

这是一个解决方案,可确保 React DevTools 正常处理我们的警告,但隐藏 UNSAFE_ 警告:

const backup = console.warn;

console.warn = function filterWarnings(warning) {
    // If the warning includes any of the following text, let's hide it.
    const supressedWarnings = [
        "Warning: componentWillMount has been renamed, and is not recommended for use.",
        "Warning: componentWillReceiveProps has been renamed, and is not recommended for use.",
        "Warning: componentWillUpdate has been renamed, and is not recommended for use.",
    ];

    if (warning.length && !supressedWarnings.some(entry => warning.includes(entry))) {
        backup.apply(console, arguments);
    }
};

答案 4 :(得分:-1)

在index.android.js中,您可以使用:

  console.disableYellowBox = true
  console.warn = () => {}