[英]React useState re rendering too many times
I am creating a simple carousel with react and I noticed that my index gets call multiple times and I don't understand why, here is my snippet of code here also here is a full version https://codesandbox.io/s/small-bash-4l7ix?file=/src/index.js我正在创建一个带有反应的简单轮播,我注意到我的索引被多次调用,我不明白为什么,这是我的代码片段,这里也是完整版本https://codesandbox.io/s/small -bash-4l7ix?file=/src/index.js
...
const pages = [
React.forwardRef((props, ref) => (
<animated.div ref={ref} style={{ ...props.style, background: 'lightpink' }}>
A
</animated.div>
)),
React.forwardRef((props, ref) => (
<animated.div ref={ref} style={{ ...props.style, background: 'lightblue' }}>
B
</animated.div>
)),
React.forwardRef((props, ref) => (
<animated.div ref={ref} style={{ ...props.style, background: 'lightgreen' }}>
C
</animated.div>
)),
]
export default function App() {
const [index, set] = useState(0)
const [containerRef, containerSize] = useDimensions()
const transitions = useTransition(index, p => p, {
from: { opacity: 0, transform: 'translate3d(100%,0,0)' },
enter: { opacity: 1, transform: 'translate3d(0%,0,0)' },
leave: { opacity: 0, transform: 'translate3d(-50%,0,0)' },
})
const divStyle = {
height: `${containerSize.height}px`,
}
console.log(index)
return (
<>
<button className={`btn ${index === 0 ? 'btn--active' : ''}`} onClick={() => set(0)}>
Slide 1
</button>
<button className={`btn ${index === 1 ? 'btn--active' : ''}`} onClick={() => set(1)}>
Slide 2
</button>
<button className={`btn ${index === 2 ? 'btn--active' : ''}`} onClick={() => set(2)}>
Slide 3
</button>
<div style={divStyle} className="simple-trans-main">
{transitions.map(({ item, props, key }) => {
const Page = pages[item]
return <Page ref={containerRef} key={key} style={props} />
})}
</div>
<p> Lorem ipusum</p>
</>
)
}
...
This is because of useTransition
.这是因为
useTransition
。
That creates an extra render of sorts, that is why you see index printed multiple times.这会产生一种额外的渲染,这就是为什么您会看到多次打印索引的原因。
I have removed the useTransition
and you can check it prints only on index
change.我已经删除了
useTransition
,您可以检查它仅在index
更改时打印。
Check below.检查下面。
In order to transition components in and out the useTransition hook from react-spring keeps track of component instances for you.为了将组件移入和移出 react-spring 的 useTransition 钩子会为您跟踪组件实例。 These extra renders are caused by overlapping mounting and unmounting of nodes.
这些额外的渲染是由节点的重叠安装和卸载引起的。
For example:例如:
Each transition is pushed into the array and the library animates them in order.每个转换都被推入数组,库按顺序对它们进行动画处理。 So you can trigger multiple overlapping animations simultaneously.
因此,您可以同时触发多个重叠动画。
Checkout the React DevTools in the codesandbox and you will see the nodes mounting and unmounting.检查代码和框中的 React DevTools,您将看到节点安装和卸载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.