首页 > 解决方案 > 我怎么知道渲染原因是在反应钩子函数中改变了属性还是改变了状态?

问题描述

我有一个由反应钩子实现的显示组件。显示组件通过名为“行”的属性接收一组记录。它有两个按钮用于显示上一个或下一个,所以我使用一个名为“索引”的状态表示当前行号。

通过减少或增加状态“索引”很容易显示上一个/下一个。但是当它的行发生变化时,我想将索引重置为零。如何在不保存行的副本来比较它们的情况下获得正确的条件?

interface row {
  id: number;
  name: string;
}
interface tableProps {
  rows: row[];
}
const Shower: React.FC<tableProps> = (props) => {
  const [index, setIndex] = useState<number>(0);
  // when should I reset the index to zero when receiving a new property rows?
  return <div>  
    <button disabled={!(index > 0)} onClick={() => setIndex(index - 1)}>Prev</button>
    <span>{props.rows[index].id}:{props.rows[index].name}</span>
    <button disabled={!(index + 1 < props.rows.length)} onClick={() => setIndex(index + 1)}>Prev</button>
  </div>;
}

标签: reactjsreact-hookssetstate

解决方案


您可以使用useEffect

......

import {useEffect} from 'react'
....

useEffect(()=>{
   setIndex(0)
},[props.rows])

推荐阅读