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