markdown React 17:`getDerivedStateFromProps`而不是`componentWillReceiveProps`

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown React 17:`getDerivedStateFromProps`而不是`componentWillReceiveProps`相关的知识,希望对你有一定的参考价值。

## React 17: `getDerivedStateFromProps` instead of `componentWillReceiveProps`

```jsx
componentWillReceiveProps(newProps) {
  if (this.props.userID !== newProps.userID) {
    this.setState({ profileOrError: undefined })
    fetchUserProfile(newProps.userID)
      .catch(error => error)
      .then(profileOrError => this.setState({ profileOrError }))
  }
}
```

:arrow_down:

```jsx
class ExampleComponent extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // Store prevUserId in state so we can compare when props change.
    // Clear out any previously-loaded user data (so we don't render stale stuff).
    if (nextProps.userId !== prevState.prevUserId) {
      return {
        prevUserId: nextProps.userId,
        profileOrError: null,
      };
    }

    // No state update necessary
    return null;
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.profileOrError === null) {
      // At this point, we're in the "commit" phase, so it's safe to load the new data.
      this._loadUserData();
    }
  }

  render() {
    if (this.state.profileOrError === null) {
      // Render loading UI
    } else {
      // Render user data
    }
  }
}
```

:arrow_right: https://github.com/reactjs/rfcs/issues/26#issuecomment-365744134

以上是关于markdown React 17:`getDerivedStateFromProps`而不是`componentWillReceiveProps`的主要内容,如果未能解决你的问题,请参考以下文章

react 将字符串解析为markdown

markdown react-router #react

markdown 演示:使用非React视图协调异步React

markdown 演示:使用非React视图协调异步React

基于 React 开发了一个 Markdown 文档站点生成工具

markdown 使用没有状态管理库的React和React Native