【问题标题】:Why counter defined with useRef hook is not incrementing on each render?为什么用 useRef 钩子定义的计数器在每次渲染时都不会递增?
【发布时间】:2019-12-24 02:50:52
【问题描述】:

我正在尝试使用钩子 useRef() 来保留接下来要显示哪些项目的计数器,并在每次渲染时递增计数器,并使用计数器值切入数组中的元素。在每次渲染中,计数器 index.current 应该增加 10,但在我的情况下,它没有增加,我一遍又一遍地得到相同的 10 个元素。我不知道为什么。这里的集合概览组件在集合预览组件上映射了 4 次。

//CollectionPreview

const CollectionPreview = ({title,movieItems,Counter}) =>  {
     const index = React.useRef(0)
     const movieData = movieItems.slice(index.current, index.current + 10)
     index.current += 10

        return (
            <div className="collection-preview">
                <h1 className="title">{title.toUpperCase()}</h1>
                  <div className="preview"> 
                    {console.log(movieData)}
                  </div>
            </div>
        );
    }

const mapStateToProps = state => ({
    movieItems: selectMovieItems(state),
})

export default connect(mapStateToProps)(CollectionPreview);


//CollectionOverview

class CollectionOverview extends React.Component {

render() {
    return (
        <div className="collection-overview">
            {
                CollectionData.map(items => 
                    <CollectionPreview key={items.id} title={items.title} />)
            }
        </div>

    );
}
}

export default CollectionOverview;

【问题讨论】:

  • 我假设您希望 CollectionOverview 中的每个 CollectionPreview 显示不同的页面?
  • 没有 CollectionOverview 是页面,每个 CollectionPreview 都是一个电影网格,就像 netflix 一样。这里虽然只有四个网格,因为 CollectionOverview 将 CollectionPreview 映射四次。

标签: javascript arrays reactjs redux


【解决方案1】:

我个人认为计算渲染次数是不好的模式,因为渲染可以在不同的场合被多次调用,并且随着你的应用变得越来越大,很难跟踪每一次渲染调用。

我认为更好的方法是在某个状态下使用initialIndexpageIndex。当您使用 Redux 时,我认为您应该将其放入 reducer 并创建适当的操作来增加此值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2021-11-02
    • 1970-01-01
    • 2021-06-23
    • 2019-11-23
    • 1970-01-01
    相关资源
    最近更新 更多