代码之家  ›  专栏  ›  技术社区  ›  arnoldbird

如何将值从React本机功能组件返回给父级

  •  0
  • arnoldbird  · 技术社区  · 8 年前

    对于此功能组件,如何将值返回给调用该功能的另一个组件?

    /**
     * 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
    

    类似的问题对我的情况没有太大帮助:

    1 回复  |  直到 8 年前
        1
  •  1
  •   ggsrivas    8 年前

    解决此问题的正确方法是使用Redux或其他商店管理器。如果您使用的是redux,则可以使用新值更新存储,并且所有组件都可以使用它。这样,您的家长就可以直接访问它。

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

    推荐文章