将setState与诺言一起使用后出现错误

vir*_*nde 22 javascript react-native

码:

onDragEnd = {
    (event) => this.setState({ playerMarkerPositionFuture: event.nativeEvent.coordinate })
    .then(() => alert("hello"))
}
Run Code Online (Sandbox Code Playgroud)

当执行以下代码时,我收到此错误:

undefined is not an object evaluating
('_this.setState({playerMarkerPositionFuture: event.nativeEvent.coordinate}).then')
Run Code Online (Sandbox Code Playgroud)

如果我删除了承诺,那么一切都会按预期进行,因此这意味着我很可能以错误的方式使用了承诺:

onDragEnd={
    (event) => this.setState({ playerMarkerPositionFuture: event.nativeEvent.coordinate })
}

Run Code Online (Sandbox Code Playgroud)

Rau*_*cco 12

setState接受回调,但不返回承诺。查看文件

对setState的调用是异步的-调用setState后不要立即依赖this.state来反映新值。如果您需要根据当前状态计算值,请传递更新器函数而不是对象(有关详细信息,请参见下文)。

(event) => {
    this.setState({playerMarkerPositionFuture: event.nativeEvent.coordinate }, () => alert("hello"));
}
Run Code Online (Sandbox Code Playgroud)


小智 5

setState不返回Promise。它很可能是void函数。


Rap*_*ada 5

在setState完成后,不要使用promise来调用警报,而应使用回调

onDragEnd={(event) => 
this.setState({ 
    playerMarkerPositionFuture: event.nativeEvent.coordinate 
}, () => {
    alert("hello")
})}
Run Code Online (Sandbox Code Playgroud)