reactjs - 我怎么知道渲染原因是在反应钩子函数中改变了属性还是改变了状态?
问题描述
我有一个由反应钩子实现的显示组件。显示组件通过名为“行”的属性接收一组记录。它有两个按钮用于显示上一个或下一个,所以我使用一个名为“索引”的状态表示当前行号。
通过减少或增加状态“索引”很容易显示上一个/下一个。但是当它的行发生变化时,我想将索引重置为零。如何在不保存行的副本来比较它们的情况下获得正确的条件?
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>;
}
解决方案
您可以使用useEffect
......
import {useEffect} from 'react'
....
useEffect(()=>{
setIndex(0)
},[props.rows])
推荐阅读
- c# - 如何在win2d UWP 中设置/更改canvasBitmap 的高度和宽度?
- reactjs - 父组件对象在没有设置状态的情况下发生变化
- excel - SAP GUI 脚本 - 创建合同标头
- google-cloud-platform - GCP-IAM - 如何授予对组织中所有服务帐户的访问权限?
- amazon-web-services - 如何使用 jq 一起打印顶级字段和内部数组字段?
- php - php Hook Error spl_object_hash() expects exactly 1 parameter, 2 given
- spring-data-rest - 使用投影创建/更新后 Spring Data REST 返回实体
- javascript - document.getElementById('input-ID').value - 对于输入 (!) - 返回 undefined
- algorithm - 轮盘选择,遗传算法
- date - 在 RPG 中,使用文件中的 *job 格式的日期