我目前正在开发与流星后端本地反应,
我在createContainer中订阅,订阅包含userId,我将使用meteor方法获取用户图片,如下面的代码所示, 但我不能让它工作,用户图片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);
答案 0 :(得分:1)
我想说这是使用组件状态的好例子。此外,最好避免使用render方法发出远程请求,因为每次组件重新渲染时都会调用它。
要发出请求,我会修改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,
});
}
})
}
然后从组件中可以呈现方法调用的结果,该结果存储在状态
中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={this.state[priceDiscuss.buyerId] ? {uri: this.state[priceDiscuss.buyerId]} : null}
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>
);
}
}
最后,您可以从componentDidMount
,componentWillReceiveProps
或其他一些生命周期方法请求数据(仅在您需要时 - 请检查状态/道具是否已更改)。
componentWillReceiveProps(nextProps) {
if (this.props.priceDiscussesSelling.length !== nextProps.priceDiscussesSelling.length) {
nextProps.priceDiscussesSelling.forEach((priceDiscuss) => {
this.getAvatar(priceDiscuss.buyerId);
});
}
}