对于我从另一个开发人员那里继承的React应用程序,其中一个页面包括:
import { getLogUser } from "../../appRedux/actions/authAction";
constructor(props) {
super(props);
this.state = {
user: null,
};
}
UNSAFE_componentWillMount() {
let user = getLogUser();
this.setState({ user });
// user state is used inside the render part
}
componentDidMount = () => {
let { username } = getLogUser();
// ... username is used inside some logic within the componentDidMount method.我想摆脱UNSAFE_componentWillMount方法。
UNSAFE_componentWillMount中使用user: getLogUser(),可以删除constructor部件吗?let { username } = getLogUser();替换componentDidMount内部的let { username } = this.state.user发布于 2022-03-31 16:09:51
首先,让我先解释一下什么是UNSAFE_componentWillMount
由定义
在挂载发生之前调用UNSAFE_componentWillMount()。在呈现()之前调用它,因此在此方法中同步调用setState()不会触发额外的呈现。
因此,这意味着UNSAFE_componentWillMount()将在render()之前被调用(组件还没有在UI上)。这与componentDidMount()完全相反,后者被称为render()
为了更深入地了解function的团队为什么想将其设置为UNSAFE,对于不推荐的函数,您可以检查这个RFC。
跟进你的问题
如果在构造函数中使用user: getLogUser(),我可以删除getLogUser部件吗?
在constructor中调用函数的好处类似于UNSAFE_componentWillMount,它确保在呈现触发器之前数据可用。
因此,对于您的情况,我会说是的,只要它不是异步函数(如async/await),您就可以这样做。
constructor(props) {
super(props);
this.state = {
user: await getLogUser(), //YOU CANNOT DO THIS WAY
};
}这是正确的方法
constructor(props) {
super(props);
this.state = {
user: getLogUser(), //no asynchronous call
};
}那么如果getLogUser()是异步的呢?componentDidMount会派上用场。它将在第一次呈现后触发,但您可以根据需要等待数据,除此之外,它不会阻止UI的交互(或者您可以显示加载UI)
componentDidMount = async () => {
const user = await getLogUser()
setState({ user })
}
render() {
//show loading if `user` data is not populated yet
const { user } = this.state
if(!user) {
return <div>Loading</div>
}
}如果这确实是正确的方法,那么我是不是也应该将let { username }= getLogUser();inside componentDidMount替换为let { username }= this.state.user?
确实是这样。如果您已经在user中填充了constructor状态,但是您需要确保您的函数将在很短的时间内执行,您就可以这样做。如果函数调用花费的时间太长,则会由于呈现阻塞而导致UI问题。
//trigger before first rendering
constructor(props) {
super(props);
this.state = {
user: getLogUser(), //no asynchronous call
};
}
//trigger after first rendering
componentDidMount = () => {
const { username } = this.state.user;
}https://stackoverflow.com/questions/71685176
复制相似问题