[英]How to setCurrent state of componet on button click with react hooks
I want to run some logic when a button is clicked and I want to change the state in that logic.我想在单击按钮时运行一些逻辑,并且我想在该逻辑中更改 state。 So far react is giving me a to many rerenders error.到目前为止,react 给了我很多重新渲染错误。 Here is my code so far到目前为止,这是我的代码
const [current, setCurrent] = useState(0)
// const [theRest, theRest] = useState(false);
const next = (order, i) => {
let nextSlide = order + 1
setCurrent(nextSlide)
if (nextSlide > i) {
nextSlide = 0
}
}
{data.allSanitySlideDeck.edges.map(({ node: slide }, i) => (
<React.Fragment key={i}>
{/* {current === slide.order && ( */}
<>
<Card>
<h1>{slide.postTitle}</h1>
<h2></h2>
<p></p>
</Card>
<button>back</button>
<button onClick={next(slide.order, i)}>next</button>
</>
// )}
</React.Fragment>
))}
onClick
expects a function inside the {}
not the result of calling a function onClick
期望{}
中的 function 不是调用 function 的结果
Try changing to:尝试更改为:
onClick={() => next(slide.order, i)}
What is basically happening is that function call is being made every time render()
occurs and causes a state update which causes a new render call and therefore a race condition基本上发生的情况是,每次render()
发生时都会进行 function 调用并导致 state 更新,这会导致新的渲染调用,因此会导致竞争条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.