【问题标题】:How to return a value from a React Native functional component to the parent如何将值从 React Native 功能组件返回给父级
【发布时间】: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


    【解决方案1】:

    解决这个问题的正确方法是使用 Redux 或其他商店经理。如果您使用的是 redux,那么您可以使用新值更新 store,它将可供所有组件使用。这样,您的父母可以直接访问它。

    fetch 操作是异步的,它不能直接将数据返回给调用方法。 如果您不想使用 redux,那么一个非常标准的 javascript 解决方案将使用回调。 您可以将回调方法传递给您的 fetch 函数。在您的代码中,您可以将return s 替换为对回调方法的调用。 例如将return s 替换为callback(s)

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 2018-12-28
      • 2020-05-30
      • 1970-01-01
      相关资源
      最近更新 更多