【问题标题】:How to set state in react whith the content at a certain index from an array如何设置状态以与数组中某个索引处的内容作出反应
【发布时间】:2021-05-05 03:47:41
【问题描述】:

我有一系列评论,我想在点击时更新评论在某个索引处的状态。有人可以解释为什么下面的代码不起作用吗?和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>

【问题讨论】:

    标签: javascript reactjs react-hooks react-state


    【解决方案1】:

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

    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>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 2016-07-06
      • 2021-10-31
      • 2020-03-19
      相关资源
      最近更新 更多