componentWillReceiveProps已重命名


10

我正在使用使用ReactSwipableView包的Material ui SwipeableViews,在控制台上收到此错误

react-dom.development.js:12466警告:componentWillReceiveProps已重命名,不建议使用。有关详细信息,请参见。

  • 将获取数据的代码或副作用移动到componentDidUpdate。
  • 如果在道具更改时要更新状态,请重构代码以使用备注技术或将其移至静态getDerivedStateFromProps。了解更多信息:
  • 将componentWillReceiveProps重命名为UNSAFE_componentWillReceiveProps以在非严格模式下禁止显示此警告。在React 17.x中,只有UNSAFE_名称起作用。要将所有已弃用的生命周期重命名为其新名称,可以npx react-codemod rename-unsafe-lifecycles在项目源文件夹中运行。

请更新以下组件:ReactSwipableView

有没有什么办法可以摆脱这个错误,我没有尝试过UNSAFE_componentWillReceiveProps但没有任何变化


1
您是否使用componentWillReceiveProps你的组件,或者是从你的包来了吗?
马丁

1
它来自react-swipeable-views软件包
Buk Lau

Answers:


8

似乎已经向维护者报告了这一情况。

现在,作为开源软件的使用者,您可以:

最终,这不是与您的软件有关的错误,而是它所依赖的依赖项。解决这些问题实际上不是您的责任。如果您的应用运行,那就没问题了。来自的警告react-dom.development.js不会出现在生产中。


2

使用getDerivedStateFromProps代替componentWillReceiveProps

例如:

之前:

// Before
class ExampleComponent extends React.Component {
  state = {
    isScrollingDown: false,
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.currentRow !== nextProps.currentRow) {
      this.setState({
        isScrollingDown:
          nextProps.currentRow > this.props.currentRow,
      });
    }
  }
}

后:

// After
class ExampleComponent extends React.Component {
  // Initialize state in constructor,
  // Or with a property initializer.
  state = {
    isScrollingDown: false,
    lastRow: null,
  };

  static getDerivedStateFromProps(props, state) {
    if (props.currentRow !== state.lastRow) {
      return {
        isScrollingDown: props.currentRow > state.lastRow,
        lastRow: props.currentRow,
      };
    }

    // Return null to indicate no change to state.
    return null;
  }
}

https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html


1

我在查找代码组件中的WillReceiveProps的位置时遇到问题。我确实在警告中注意到它提到了一个特定的组件“ Drawer”,它是我们正在使用的ant-d lib的一部分。将ant-d升级到最新版本后,警告消失了。


1

这是React Native项目中发生的常见错误,因此可以通过以下步骤解决:

  • 首先在您的本机项目目录中安装lodash,即
npm i --save lodash

-之后,在您的.js文件中编写以下代码:

    import { YellowBox } from 'react-native';
    import _ from 'lodash';

    YellowBox.ignoreWarnings(['componentWillReceiveProps']);
    const _console = _.clone(console);
    console.warn = message => {
    if (message.indexOf('componentWillReceiveProps') <= -1) {
     _console.warn(message);
    } 
   };
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.