使用react hooks设置值的问题

我是钩子的新手,在使用钩子时遇到问题。我有两个组成部分:


const Button = ({ isHidden, icon, onClick }) => {

  return (

    <div>

      {isHidden ? (

        <button className="tile" onClick={onClick} />

      ) : (

        <button className="tile" onClick={onClick}>

          <i className={icon} />

        </button>

      )}

    </div>

  );

};


const Board = () => {

  const [isHidden, setIsHidden] =useState(Array(12).fill(true));

  const [icon] = useState(animalArray);


  const renderButton = index => {

    return (

      <Button

        icon={icon[index]}

        isHidden={isHidden[index]}

        onClick={() =>setIsHidden(!isHidden[index])}

      />

    );

  };

  return (

    <div className="board">

      <div className="container">

        <div className="row align-items-start">

          <div className="col-3">{renderButton(0)}</div>

          <div className="col-3">{renderButton(1)}</div>

          <div className="col-3">{renderButton(2)}</div>

因此,我当然想在单击其按钮后在特定图块中切换isHidden状态。取而代之的是,我在第一次单击时翻转了所有磁贴,然后在随后的单击中没有任何反应。我尝试修改它,例如创建新变量,复制isHidden等。谢谢。


慕码人2483693
浏览 270回答 3
3回答

catspeake

由于状态更新程序不会合并状态,因此您需要将整个更新后的状态传递给更新程序并使用回调模式。您还需要返回该数组的新实例,而不是对其进行修改,否则状态更新器将不会检测到更改并且它不会重新呈现const renderButton = index => {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <Button&nbsp; &nbsp; &nbsp; &nbsp; icon={icon[index]}&nbsp; &nbsp; &nbsp; &nbsp; isHidden={isHidden[index]}&nbsp; &nbsp; &nbsp; &nbsp; onClick={() =>setIsHidden(prevHidden => Object.assign([], prevHidden, {[index]: !prevHidden[index])}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; );&nbsp; };

胡说叔叔

该onClick应onClick={() => setIsHidden(&nbsp; isHidden.map((hidden, hiddenIndex) => (&nbsp; &nbsp; index === hiddenIndex ? !hidden : hidden&nbsp; )))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript