如何设置状态以与数组中特定索引处的内容做出反应

How to set state in react whith the content at a certain index from an array

我有一系列评论,我想在点击时更新某个索引处的评论状态。有人可以解释为什么下面的代码不起作用吗?和mabie提供解决方案?评论通过道具传递。控制台日志显示 2、2、3,然后再次显示 2,2 3。我有 5 条评论。奇怪的是,如果我评论 setReview 行,控制台会按预期显示。

const InfoSection = ({ reviews}) => {
 let index = 1;
 let [review, setReview] = useState('some initial state');

 const paintNextReview = () => {
  //   index >= reviews.length ? (index = 0) : (index = index);
  setReview(reviews[index]);
   index++;
  console.log(index);
  
 };
 return(
 <div>
 
          <div >{review}</div>
          <button onClick={paintNextReview}> click</button>
 </div>
 )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

是的,您也需要将索引作为状态变量:

const InfoSection = ({ reviews }) => {
  let [index, setIndex] = useState(1); // or should it be 0?
  let [review, setReview] = useState('some initial state');

  const paintNextReview = () => {
    setReview(reviews[index]);
    setIndex(index + 1);
  };
  return (
    <div>
      <div>{review}</div>
      <button onClick={paintNextReview}> click</button>
    </div>
  );
};