Установите состояние в getDerivedStateFromProps (установите состояние, реагируйте)

#reactjs #react-native #components #state #getderivedstatefromprops

#reactjs #реагировать-родной #Компоненты #состояние #getderivedstatefromprops

Вопрос:

В компонент класса я попал:

 state = {
       user: {}      
}

componentWillMount() {
    firebaseAuth.onAuthStateChanged((user) => {
        
        if(user) {
            this.setState({
                user: {
                    id: user.uid,
                    email: user.email
                }
            })
        }

    })
   }
 

Но в консоли я получил информацию о том, что:

 react-dom.development.js:67 Warning: componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.

* Move code with side effects to componentDidMount, and set initial state in the constructor.
* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.
 

Так что я пытаюсь это исправить:

  static getDerivedStateFromProps(props, state) {  

    firebaseAuth.onAuthStateChanged((user) => {

        if(user) {
           return{               
                user:{
                    id: user.uid,
                    email: user.email
                }
           }         
        }
    })
    
    return null;
  }
 

Но состояние не обновляется (не установлено). Что я делаю не так? Как это исправить?

Ответ №1:

getDerivedStateFromProps не буду ждать ответа

у вас есть 2 решения для удаления предупреждения

1 . переименуйте имя метода componentWillMount в UNSAFE_componentWillMount

2: отправить запрос в componentDidMount

 componentDidMount() {
    firebaseAuth.onAuthStateChanged((user) => {
        
        if(user) {
            this.setState({
                user: {
                    id: user.uid,
                    email: user.email
                }
            })
        }

    })
   }
 

Комментарии:

1. для UNSAFE_componentWillMount меня тоже предупреждение, но componentDidMount все в порядке, так что спасибо @Mehran за помощь