Reactjs componentWillMount中的链接api-异步等待或承诺
因此,在登录之后,我将在cookie中有一些值,我需要将这些值设置为redux,然后调用另一个api。所以在登录后,我会在cookie中有自己的名字。因此,我将获取name值并在redux中设置,一旦完成,我将从cookie中清除该名称。在清除这些值之后,我需要获取redux中设置的名称,并传递该名称以调用componentWillMount中的另一个apiReactjs componentWillMount中的链接api-异步等待或承诺,reactjs,Reactjs,因此,在登录之后,我将在cookie中有一些值,我需要将这些值设置为redux,然后调用另一个api。所以在登录后,我会在cookie中有自己的名字。因此,我将获取name值并在redux中设置,一旦完成,我将从cookie中清除该名称。在清除这些值之后,我需要获取redux中设置的名称,并传递该名称以调用componentWillMount中的另一个api componentWillMount(){ this.props.setDetailsToRedux() clearCookie(
componentWillMount(){
this.props.setDetailsToRedux()
clearCookie()
this.props.anotherApiCall(this.props.currentUser.name)
}
那么,如果我使用async await,我该怎么做呢。如何使用它如果在redux中设置名称后清除了cookie,则无需在cookie中设置名称。在redux中设置名称后,您可以从登录直接在redux中设置名称。您将在redux的任何位置找到该名称。如果在redux中设置名称后清除cookie,则无需在cookie中设置名称。您可以从登录直接在redux中设置名称,在redux中设置后,您将在redux的任何位置找到该名称。首先,
componentWillMount
不是进行API调用的正确位置,只需在componentDidMount
中使用它即可
组件将挂载/不安全\u组件将挂载
如果您是第一次看到不安全
,让我在几天前发布的React v16.3.0中告诉您,组件将挂载
仅在版本17之前有效,并且不安全
将作为前缀以允许逐步迁移。
这是不使用此方法的一个非常有力的理由
过去,React社区曾进行过一场激烈的辩论和讨论,反对使用组件willmount
,而改用构造函数,因此就这样做了
社区中React开发人员普遍存在这样一种误解,即我们应该在componentWillMount
中调用API,以防止额外的渲染。但事实是,render方法总是在componentWillMount之后立即调用,无法要求render等待API调用完成
Ref:首先,componentWillMount
不是进行API调用的正确位置,只需在componentDidMount
中使用它即可
组件将挂载/不安全\u组件将挂载
如果您是第一次看到不安全
,让我在几天前发布的React v16.3.0中告诉您,组件将挂载
仅在版本17之前有效,并且不安全
将作为前缀以允许逐步迁移。
这是不使用此方法的一个非常有力的理由
过去,React社区曾进行过一场激烈的辩论和讨论,反对使用组件willmount
,而改用构造函数,因此就这样做了
社区中React开发人员普遍存在这样一种误解,即我们应该在componentWillMount
中调用API,以防止额外的渲染。但事实是,render方法总是在componentWillMount之后立即调用,无法要求render等待API调用完成
Ref:您可以在React生命周期方法中使用async/await
。请记住向函数中添加async:
async componentDidMount() {
const someValue = await doFirstThing()
await doSomethingWithValue(someValue)
}
如果渲染方法取决于此进程的状态,请添加一些本地状态:
constructor() {
this.state = {
isReady: false
}
}
async componentDidMount() {
const someValue = await doFirstThing()
await doSomethingWithValue(someValue)
this.setState({isReady: true})
}
render() {
if (!this.state.isReady) {
return null /* or a loader/spinner */
}
return "I'm loaded ok."
}
另外,请务必阅读其他答案,因为他们对您的代码有合理的顾虑。您可以在React生命周期方法中使用async/await
。请记住向函数中添加async:
async componentDidMount() {
const someValue = await doFirstThing()
await doSomethingWithValue(someValue)
}
如果渲染方法取决于此进程的状态,请添加一些本地状态:
constructor() {
this.state = {
isReady: false
}
}
async componentDidMount() {
const someValue = await doFirstThing()
await doSomethingWithValue(someValue)
this.setState({isReady: true})
}
render() {
if (!this.state.isReady) {
return null /* or a loader/spinner */
}
return "I'm loaded ok."
}
另外,请务必阅读其他答案,因为他们对您的代码有充分的顾虑。在询问之前,您是否确实尝试过async/await?有什么问题吗?此外,componentWillMount也被弃用,因为它经常被误用。此代码属于componentDidMount。为什么不在登录中设置该名称?在询问之前是否确实尝试了async/await?有什么问题吗?此外,componentWillMount也被弃用,因为它经常被误用。此代码属于componentDidMount。为什么不在登录中设置该名称?