2017-05-14 91 views
0

我目前的发展作出反应本地人,有着流星后端,流星方法调用的阵营本地没有反应

我在createContainer订阅和订阅包含用户id,我会用一颗流星的方法来获取用户的图片作为下面的代码, ,但我不能使它的工作,用户图片uri永远不会到组件...

任何人都可以帮助我吗? 你认为什么是最好的做法,当涉及异步数据处理的反应原生&流星?

非常感谢你!

getAvatar(buyerId){ 
    Meteor.call('getUserPicture', buyerId, (err, res)=>{ 
     if(err){ 
     console.log(err); 
     return err; 
     } 
     else{ 
     console.log(res); 
     return res; 
     } 
    }) 
    } 

    render() { 
    if(this.props.handle.ready()){ 
     return (
     <View> 
     <ScrollView > 
     <List containerStyle={{marginBottom: 20}}> 
     { 
      this.props.priceDiscussesSelling && this.props.priceDiscussesSelling.map((priceDiscuss, i) => { 

      return (<ListItem 
       roundAvatar 
       avatar={{uri: this.getAvatar(priceDiscuss.buyerId)&&this.getAvatar(priceDiscuss.buyerId)}} 
       key={i} 
       subtitle={priceDiscuss.lastDiscussItem.createdAt} 
       rightTitle={priceDiscuss.status} 
       title={priceDiscuss.lastDiscussItem.content} 
       onPress={()=>{this.props.navigation.navigate('PriceDiscussDetail', {priceDiscussId: priceDiscuss._id})}} 
       />) 
      } 
     ) 
     } 
     </List> 

     </ScrollView> 

     </View> 
    ); 
    } 
    } 

export default createContainer(param => { 
    let handle = Meteor.subscribe('getPersonalSellingPriceDiscusses',(err)=>{ 
     if(err){ 
     console.log(err); 
     } 
     else{ 
     } 
    }); 
    return { 
     priceDiscussesSelling: Meteor.collection('priceDiscusses').find({ sellerId : Meteor.userId()}), 
     handle: handle 
    } 
    }, PriceDiscussSelling); 

回答

1

我会说这是使用组件状态的好例子。此外,避免从渲染方法发出远程请求是一个好主意,因为它每当组件重新呈现时都会被调用。

为了提出请求,我会修改getAvatar函数,将结果写入状态。

getAvatar(buyerId){ 
    Meteor.call('getUserPicture', buyerId, (err, res)=>{ 
    if(err){ 
     console.log(err); 
     return err; 
    } 
    else{ 
     console.log(res); 
     const updatedState = {}; 
     updatedState[buyerId] = res; // there may be a more succinct way of doing this 
     this.setState({ 
     ...this.state, // ensure current state gets copied 
     ...updatedState, 
     }); 
    } 
    }) 
} 

然后从组件中可以渲染的方法调用,存储在状态

​​

的结果终于可以从componentDidMountcomponentWillReceiveProps或其他一些使对数据的请求生命周期方法(只有当你需要时 - 检查状态/道具是否有变化)。

componentWillReceiveProps(nextProps) { 
    if (this.props.priceDiscussesSelling.length !== nextProps.priceDiscussesSelling.length) { 
    nextProps.priceDiscussesSelling.forEach((priceDiscuss) => { 
     this.getAvatar(priceDiscuss.buyerId); 
    }); 
    } 
} 
+0

哇,这是斯宾塞,我刚刚读了你的博客文章,和其他反应生命周期文章,试图找出如何捕捉更新的数据。很高兴有你的帮助,你的解决方案就像一个魅力!我会继续跟随你的工作来回应原生和流星,如果我有时间,也许会采取一些你的课程。伟大的工作人员,非常感谢你! – Nan

+0

哈哈很高兴我能帮忙!希望在课程中看到您,如果您有任何其他问题,我很乐意提供帮助! –

+0

嗨,我的问题是当我在流星调用中调用setState时出现错误,说this.setState不是函数。你有什么想法,为什么会这样。我在构造函数中绑定了这个函数。 @SpencerCarli我读过你的中文文章,非常感谢 – picacode