Set State into getDerivedStateFromProps (set state, React)

Posted

技术标签:

【中文标题】Set State into getDerivedStateFromProps (set state, React)【英文标题】: 【发布时间】:2021-03-09 09:35:19 【问题描述】:

进入类组件我得到了:

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
                
            )
        

    )
   

【讨论】:

对于UNSAFE_componentWillMount 我也收到警告,但componentDidMount 没问题,所以谢谢@Mehran 的帮助

以上是关于Set State into getDerivedStateFromProps (set state, React)的主要内容,如果未能解决你的问题,请参考以下文章

A Deep Dive into Rescalable State in Apache Flink

A Deep Dive into Rescalable State in Apache Flink

[Functional Programming] Compose Simple State ADT Transitions into One Complex Transaction

REPLACE INTO 和 INSERT INTO ... ON DUPLICATE KEY UPDATE SET ...

REPLACE INTO 和 INSERT INTO ... ON DUPLICATE KEY UPDATE SET ...

select into outfile写文件时路径包含中文解决办法