首页 > 解决方案 > React Native:在承诺之外重用承诺参数?

问题描述

我定义了一个获取查询的承诺。我有一个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参数吗?

标签: react-nativepromise

解决方案


我们又来了@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>
  )
}

推荐阅读