【发布时间】:2018-10-12 22:09:42
【问题描述】:
对于这个函数式组件,我如何才能将值返回给另一个调用该函数的组件?
/**
* A custom fetch wrapper.
*/
import Config from '../config'
const _Fetch = (context: Object, endpoint: string, init: Object, key?: string) => {
var k = (typeof key !== 'undefined') ? key : 'data';
return fetch(Config.base+endpoint, init)
.then(response => {
if (response.ok) {
response.text().then((text) => {
var obj = tryParseJSON(text)
if (obj) {
// For jsonapi.
if (obj.data) {
obj = obj.data
}
var s = {
data: Object
}
s[k] = obj
context.setState(s)
return s // This value exists here, but how can I return it to the _Fetch caller?
}
})
.catch((error) => {
console.error(error)
})
}
})
function tryParseJSON(jsonString) {
try {
var o = JSON.parse(jsonString)
if (o && typeof o === "object") {
return o
}
}
catch (e) {
console.log(e)
}
return false
}
}
export default _Fetch
当我尝试在另一个函数中获取值时,它是未定义的:
var myVar = _Fetch(context, end, init, key)
console.log(myVar); // undefined
对我的情况没有太大帮助的类似问题:
【问题讨论】:
标签: react-native fetch