【发布时间】:2020-11-23 01:05:43
【问题描述】:
方法 switchSection 应该改变当前显示部分的索引以显示下一个部分,索引被声明为当前状态,每当用户点击回车键时 switchSection 方法执行,如果当前显示部分是列表中最新的,则 setCurrent应设置为零,否则加一。一切似乎都很好,但 setCurrent 并没有修改当前状态
export default () =>{
const refs = []
//Here is the state declaration
const [current, setCurrent] = useState(0)
useEffect(() => {
window.addEventListener('keyup', switchSection)
return _ => window.removeEventListener('keyup', switchSection)
}, [])
const switchSection = event => {
if(event.keyCode === 13) {
refs[current].current.classList.remove('activeTabLink')
//the line below does not change the state, the current remains 0
current < refs.length - 1 ? setCurrent(prevVal => prevVal + 1) : setCurrent(0)
refs[current].current.classList.add('activeTabLink')
}
}
const changeActiveElement = (event) => {
let buttons = Array.from(document.getElementsByClassName('tabLinks'))
buttons.forEach(button => button.classList.remove('activeTabLink'))
event.target.classList.add('activeTabLink')
setCurrent(parseInt(event.target.id))
}
return (
<div style={SSS()}>
<Chapter additionalStyle={{textAlign: 'left', marginLeft: '2%'}}>Chapter</Chapter>
<div className="tab">
{history.links.map((link, index) => {
const newRef = useRef(null);
refs.push(newRef);
if (index === 0) return <button className="tabLinks activeTabLink" ref={newRef} id={index} onClick={changeActiveElement} key={index}>{link}</button>
else return <button className="tabLinks" ref={newRef} id={index} onClick={changeActiveElement} key={index}>{link}</button>
})}
</div>
<div className="aboutContent">
</div>
</div>
)
}
块引用
【问题讨论】:
-
您的错误在这里。 setCurrent(prevVal => prevVal + 1) 将该逻辑抽象为一个常量,然后在您的三元组上再次传递它。
标签: reactjs react-hooks setstate use-state