【问题标题】:React Native: reuse promise parameter outside the promise?React Native:在承诺之外重用承诺参数?
【发布时间】:2018-12-07 04:56:14
【问题描述】:

我定义了一个获取查询的承诺。我有一个 json 数组:

    fetch('query')
    .then(response =>response.json())
    .then(json => { blabla})

我想在promise之外重用json作为函数参数:

     render(){
     return(
    <View onLayout={this.myFonction(json)>
    </View>)}

    myFunction =(json)=>{ 
     var array = json.names
     array.maps(value => {
      return (
      <Icon        
        name='heart'
        type='emo'
        color='red'          
        onPress={this.onPressIcon(value)} />);
      });
    }

我得到的只是它是未定义的。 甚至可以重用一个promise参数吗?

【问题讨论】:

  • 用产生问题的实际代码更新您的问题。
  • .then(myFunction)?
  • 我更新了我的问题
  • 你的onLayout 表达式中的json 来自哪里?不,不等待就无法从承诺中获得价值。
  • 因为我没有找到在我看来调用我的函数的方法。我知道这很糟糕

标签: react-native promise


【解决方案1】:

我们又来了@danaso :)。尝试以这种方式实现您的组件。

您的 fetch 方法将设置组件状态:

fetch('query')
.then(response =>response.json())
.then(json => { this.setState({ array: json.names })})

所以在渲染方法中:

render(){
  const { array } = this.state;
  return(
    <View>
      array.map(value => {
        return (
          <Icon        
            name='heart'
            type='emo'
            color='red'          
            onPress={this.onPressIcon(value)} />
        )
      })
    </View>
  )
}

【讨论】:

  • 你在哪里调用你的 fetch 函数?我会把它放在componentDidMount()
猜你喜欢
  • 2019-11-23
  • 1970-01-01
  • 2016-09-18
  • 2019-06-18
  • 1970-01-01
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多