React Native:状态改变后不能重新渲染图像

时间:2018-05-05 07:33:39

标签: react-native rerender react-component

我从反应原生开始。 我从giphy API请求一个gif然后更新我的giphyUrl状态(状态被更改)但gif没有改变(组件没有被重新渲染)。

class QuoteList extends Component {
  state = { quotes: [],
            giphyUrl: 'https://media.giphy.com/media/nZQIwSpCXFweQ/giphy.gif'
          };

  componentWillMount() {
    console.log('Again?')
    axios.get('https://api.tronalddump.io/search/quote?query='+this.props.characterName)
      .then(response => this.setState({ quotes: response.data._embedded.quotes }))
    this.getGiphy()
  }

  getGiphy() {
    console.log('getgif')
    const GiphyUrl = "https://api.giphy.com/v1/gifs/search?api_key=tutu&limit=1&q=" + this.props.characterName.replace(" ", "+");
    console.log(GiphyUrl)
    axios.get(GiphyUrl)
      .then(response => {
                  console.log(response)
                  console.log(response.data.data[0].url)

                  this.setState({ giphyUrl: response.data.data[0].url })
                  console.log(this.state)
                })

  }

  renderQuotes() {
    return this.state.quotes.map(
      quote => <QuoteDetail key={quote.quote_id} quote={quote}/>
    );
  }
  render() {
    return (
      <ScrollView>
      <Image
        source={{uri: this.state.giphyUrl}}
        style={styles.gifStyle}
      />

        {this.renderQuotes()}
      </ScrollView>
    );
  }
}

为什么组件没有重新渲染?当我在axios请求的回调中调度状态时,我可以看到状态发生了变化。即使我试图强迫&#34;重新渲染(forceUpdate),它不会重新渲染。

2 个答案:

答案 0 :(得分:0)

尝试更新图片的key属性:

<Image
    source={{uri: this.state.giphyUrl}}
    key={this.state.giphyUrl}
    style={styles.gifStyle}
/>

答案 1 :(得分:0)

只要更改key,就将key道具添加到任何视图将导致视图的重新渲染。

相关问题