React Native: невозможно повторно визуализировать изображение после изменения состояния

Я начинаю с react-native. Я запрашиваю гифку из API giphy, а затем обновляю свой 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>
    );
  }
}

Почему компонент не перерисовывается? когда я console.log состояние в обратном вызове запроса axios, я вижу, что состояние изменилось. Даже когда я пытаюсь "принудительно" выполнить повторный рендеринг (forceUpdate), он не выполняет повторный рендеринг.


person David Geismar    schedule 05.05.2018    source источник


Ответы (2)


Попробуйте обновить свойство key изображения:

<Image
    source={{uri: this.state.giphyUrl}}
    key={this.state.giphyUrl}
    style={styles.gifStyle}
/>
person M Reza    schedule 05.05.2018

Добавление опоры key к любому представлению вызовет повторную визуализацию представления, пока key изменяется.

person houssameddin    schedule 23.05.2020