首页 > 解决方案 > 如何确保 React 钩子中的状态不会过时

问题描述

我在下面创建的按钮似乎落后于selectedButtonIdx价值。

被称为toggleSelected不完整的时间getClass

function ButtonGroup(props) {
    const [selectedButtonIdx,setIdx]=useState(props.loadCurrentAsIndex);

    const toggleSelected = (e) => {
        setIdx(parseInt(e.target.dataset.index));
        props.onclick(e);
    };

    const getClass = (index) => {
        return (selectedButtonIdx === index) ? classnames('current', props.btnClass)
            : classnames(props.btnClass)
    };

    let buttons = props.buttons.map((b, idx) => <Button key={idx} value={b.value} index={idx} text={b.text}
                                                        onclick={e => toggleSelected(e)}
                                                        btnClass={getClass(idx)}/>);

    return (
        <div>
            {buttons}
        </div>
    );
}

每个 onclick 都希望通过更改其类向用户显示组中的哪个按钮被单击。

标签: javascriptreactjsreact-hooks

解决方案


看着这个,

<Button 
  key={idx} 
  value={b.value} 
  index={idx} 
  text={b.text}
  onclick={e => toggleSelected(e)}
  btnClass={getClass(idx)}
/>

Button是您的自定义组件,

这里需要注意两点,

  1. 您提供了onclickc很小的)道具,在您的实际组件中应该是onClick={props.onclick}
  2. 您已经使用e.target.dataset.index, 来处理dataset我们应该有带data-前缀的属性。所以你index应该data-index在你的实际组件中。

所以最后你的Button组件应该是,

const Button = (props) => {
  return <button text={props.text} data-index={props.index} onClick={props.onclick} className={props.btnClass}>{props.value}</button>
}

演示


推荐阅读