Set State 进入 getDerivedStateFromProps (set state, React)
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;
}
但状态未更新(未设置)。我做错了什么?如何解决?
getDerivedStateFromProps
不会等待响应
您有 2 个解决方案可以消除警告
1 : 将方法名称 componentWillMount
重命名为 UNSAFE_componentWillMount
2 : 在 componentDidMount
中发送请求
componentDidMount() {
firebaseAuth.onAuthStateChanged((user) => {
if(user) {
this.setState({
user: {
id: user.uid,
email: user.email
}
})
}
})
}
进入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;
}
但状态未更新(未设置)。我做错了什么?如何解决?
getDerivedStateFromProps
不会等待响应
您有 2 个解决方案可以消除警告
1 : 将方法名称 componentWillMount
重命名为 UNSAFE_componentWillMount
2 : 在 componentDidMount
componentDidMount() {
firebaseAuth.onAuthStateChanged((user) => {
if(user) {
this.setState({
user: {
id: user.uid,
email: user.email
}
})
}
})
}