[英]React: How to use getDerivedStateFromProps() to set component state. It interferes with controlled component that uses the same state variable
[英]Set State into getDerivedStateFromProps (set state, React)
進入class 組件我得到:
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;
}
但是 state 沒有更新(沒有設置)。 我做錯了什么? 如何解決?
getDerivedStateFromProps
不會等待響應
你有 2 個解決方案來消除警告
1:將方法名componentWillMount
重命名為UNSAFE_componentWillMount
2:在componentDidMount
中發送請求
componentDidMount() {
firebaseAuth.onAuthStateChanged((user) => {
if(user) {
this.setState({
user: {
id: user.uid,
email: user.email
}
})
}
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.