2017-07-31 96 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'中的狀態。 –