3

我从 react-native 开始。我从 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 请求的回调中 console.log 状态时,我可以看到状态发生了变化。即使我尝试“强制”重新渲染(forceUpdate),它也不会重新渲染。

4

2 回答 2

9

尝试更新key图像的属性:

<Image
    source={{uri: this.state.giphyUrl}}
    key={this.state.giphyUrl}
    style={styles.gifStyle}
/>
于 2018-05-05T07:40:34.147 回答
2

key道具添加到任何视图都会导致视图的重新渲染,只要它key正在更改。

于 2020-05-23T12:41:34.507 回答