我正在使用fetch将一些JSON数据发送到具有PUT方法的服务器.当且仅当服务器响应为正时,我想弹出到上一页.
这是我的代码:
async myPutFunction() {
console.log(this.props); //here props are defined!
var dataArray=[]; //array with data to be sent
//operations on dataArray
await fetch('http://myURL', {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(dataArray)
}).then(function(res) {
if (res.status===200) {
console.log("OK!")
console.log(this.props); //here props are undefined
this.props.navigator.pop();
} else {
console.log("error: "+res.status);
}
})
}
Run Code Online (Sandbox Code Playgroud)
但是,在'then'块中,props是未定义的,this.props.navigator.pop()会抛出异常.
我的put函数在render()中以这种方式调用:
<TouchableOpacity style={styles.saveStyle}
activeOpacity={0.5}
onPress={this.myPutFunction.bind(this)}>
<Image source={saveImg} style={{resizeMode: 'cover'}} />
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚为什么道具在代码部分内部未定义,而在myPutFunction()的其余部分中定义