反应:状态更新时UI闪烁

时间:2019-03-06 21:06:39

标签: javascript reactjs react-apollo apollo-client react-hooks

我有一个组件,用于显示从Spotify API返回的搜索数据。但是,每次更新状态时,UI都会闪烁:

enter image description here 输入:

            <DebounceInput
                debounceTimeout={300}
                onChange={handleChange}
            />

挂钩:

const [searchResults, setSearchResults] = useState(null)

使用Apollo进行API调用:

 const searchSpotify = async (query) => {
    const result = await props.client.query({
        query: SearchTracks,
        variables: {
            query
        }
    })
    const tracks = result.data.searchedTracks
    setSearchResults(tracks)
}

渲染:

        {searchResults &&
            <div className="search-results">
                    {searchResults.map((song) => (
                            <SongInfo key={song.id} {...song} />
                    ))}
            </div>
        }

我注意到它仅在第一次加载时发生。例如,如果我再次键入查询,它将显示而不会闪烁。有没有更好的方法可以实现此目的,以使UI不会闪烁?

2 个答案:

答案 0 :(得分:1)

我认为发生的事情是您正在对每个导致奇怪行为的按键进行搜索查询。

使用lodash防反跳可避免对每个按键进行搜索。 那应该解决闪烁的问题。 (此外,添加加载状态会有所帮助)

样本去抖动组件

import React, {Component} from 'react'
import { debounce } from 'lodash'

class TableSearch extends Component {

  //********************************************/

  constructor(props){
    super(props)

    this.state = {
        value: props.value
    }

    this.changeSearch = debounce(this.props.changeSearch, 250)
  }

  //********************************************/

  handleChange = (e) => {
    const val = e.target.value

    this.setState({ value: val }, () => {
      this.changeSearch(val)
    })
  }

  //********************************************/

  render() {

    return (
        <input
            onChange = {this.handleChange}
            value = {this.props.value}
        />
    )
  }

  //********************************************/

}

答案 1 :(得分:1)

下面是引起闪烁的帧。我认为正在发生的事情是图像加载需要一些时间。当它们装载时,物品的高度降低了。您应该确保SongInfo的布局不取决于图像是否已加载。

未加载图片-折叠的物品:

enter image description here

图像已加载:

enter image description here