【问题标题】:React Native: Cant rerender Image after state changeReact Native:状态更改后无法重新渲染图像
【发布时间】:2018-10-15 15:36:01
【问题描述】:

我从 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),它也不会重新渲染。

【问题讨论】:

    标签: react-native rerender react-component


    【解决方案1】:

    尝试更新图片的key属性:

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

    【讨论】:

    • 救了我的命! _/_
    【解决方案2】:

    只要key 发生变化,将key 属性添加到任何视图都会导致视图重新呈现。

    【讨论】:

      猜你喜欢
      • 2018-12-27
      • 2020-09-03
      • 1970-01-01
      • 2021-06-25
      • 2018-12-12
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多