2017-07-31 99 views
0

我正在使用API​​来获取图像URL。我能够正确获取图片网址。但有时少数图像不能渲染。React-Native:图像渲染不一致

反应原生代码有问题吗?

var productDetail = this.state.result[i]; 
this.state.product.push(
    <View key = {i} style={{margin: 0.5, borderWidth: 10, borderColor: 'white', backgroundColor: 'white'}}> 
    <Image 
     resizeMode={'contain'} 
     style={{width: width/2.35, height: 180,}} 
     source={{uri: "https://abcd.in"+productDetail.image_url}}> 
    </Image> 
    </View> 

渲染,如:

<View> 
    {product} 
</View> 
+3

不要变异状态直接就不会导致重新呈现,使用的setState看到这个https://stackoverflow.com/问题/ 41376203 /为什么我不能在我的状态阵列中反应js/41376329#41376329 –

+0

正如@ShubhamKhatri所说,这个问题是因为你更新你的应用程序的方式。你不应该改变状态,而应该使用setState来触发重新渲染。这就是行为不一致的原因。 –

+0

为了扩大对我以前的评论,你将有: 'addProduct命令=()=> { this.setState({ 产品:product.concat( <查看键= {I}风格= {{保证金:0.5, borderWidth:10,borderColor:'white',backgroundColor:'white'}} ) }); }' –

回答

0

更新答:

var productDetail = this.state.result[i]; 
var products = this.state.product.slice(); 

products.push(
    <View key = {i} style={{margin: 0.5, borderWidth: 10, borderColor: 'white', backgroundColor: 'white'}}> 
     <Image 
      resizeMode={'contain'} 
       style={{width: width/2.35, height: 180,}} 
       source={{uri: "https://abcd.in"+productDetail.image_url}}> 
     </Image> 
    </View>) 

this.setState({ 
    product: products 
}) 
+2

这绝对不是问题,请查看[文档](https://facebook.github.io/react-native/docs/image.html)。 – NiFi

+0

通过这样做我得到这个错误:无法在现有状态转换期间更新(例如在'render'或另一个组件的构造函数中)。渲染方法应该是道具和状态的纯粹功能;构造函数的副作用是反模式,但可以移动到'componentWillMount'。 – subhajit

+0

更新'componentDidMount'或'componentWillReceiveProps'中的状态。 –