gpt4 book ai didi

javascript - 来自 React 组件的异步/等待调用操作

转载 作者:行者123 更新时间:2023-12-01 02:03:44 26 4
gpt4 key购买 nike

我有一个方法lookupComplete在调用操作的 react 组件中 checkIfAssign ,我需要等待响应并依赖于此方法中的此响应触发另一个方法。但收到Promise {<pending>} "result" 。如何等待解决此操作?

组件:

export class Test extends Component {
....

lookupComplete = (tagId = this.state.tagId) =>
this.setState({tagId}, () => {
let result = this.props
.checkIfAssign(this.state.tagId, this.props.accessToken)

result.status
? this.triggerTransition(transitions.ClickCheckTag)
: this.triggerTransition(transitions.Test)
})
}

export const mapDispatchToProps = dispatch => ({
checkIfAssign: (tagId, accessToken) =>
dispatch(TagAssignmentActions.checkTagAssignment(tagId, accessToken)),
})

行动:

export const checkTagAssignment = (tagId, token) => async dispatch => {
dispatch({
type: TagAssignmentActionTypes.TagAssignmentChanged,
})

let status, assignee, response
try {
response = await DeviceApi.checkTagAssignment(tagId, token)

assignee = response.result.assignee
status = response.result.status
} catch (e) {
if (e && e.status === httpStatusCode.notFound)
status = TagStatus.NotFound
}

dispatch({
type: TagAssignmentActionTypes.TagAssignmentChanged,
status,
assignee,
response,
})
console.log(response, 'response')
return response
}

最佳答案

如果你想等待,你应该让你的函数异步:

lookupComplete = async (tagId = this.state.tagId) => 
...

let result = await this.props
.checkIfAssign(this.state.tagId, this.props.accessToken)

但是,这是一个不好的模式。正确的方法是从您的应用状态中读取状态。如您所见,您的操作将在此处更新应用程序状态:

dispatch({
type: TagAssignmentActionTypes.TagAssignmentChanged,
status,
assignee,
response,
})

如果您正确执行 redux,您的 Test 组件可能会通过 connect() 进行 redux。在您的 mapStatesToProps 中,您会将 status 的值从应用状态传递到 Test 组件 props

const mapStateToProps = state => ({
status: state.myNamespaceForTaskAssignment.status,
});

然后里面getDerivedStateFromProps(nextProps, prevState)你会检查:

nextProps.status 
? this.triggerTransition(transitions.ClickCheckTag)
: this.triggerTransition(transitions.Test)

或者类似的东西。

关于javascript - 来自 React 组件的异步/等待调用操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50295036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com