我有一个由react hook实现的显示组件。显示组件通过名为“ rows”的属性接收一组记录。它有两个按钮用于显示上一个或下一个,因此我使用一个名为“ index”的状态来表示当前行号。
通过减少或增加状态“索引”很容易显示上一个/下一个。 但是,当其行更改时,我希望将索引重置为零。如何在不保存行副本进行比较的情况下获得正确的条件?
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>;
}
答案 0 :(得分:2)
您可以使用useEffect
......
import {useEffect} from 'react'
....
useEffect(()=>{
setIndex(0)
},[props.rows])
答案 1 :(得分:2)
在这种情况下,我建议您使用useEffect
(请参阅docs)
const Shower: React.FC<tableProps> = (props) => {
const [index, setIndex] = useState<number>(0);
useEffect(() => {
setIndex(0)
},[props.rows])
// 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>;
}
答案 2 :(得分:2)
您可以使用useEffect
,例如:
import React, { useEffect } from 'react';
const Shower = (props) => {
const [index, setIndex] = useState<number>(0);
useEffect(() => {
setIndex(0)
}, [props.rows.length])
// ... rest of the code
}
}
在上面的代码中,每当行的长度更改时,索引的索引值就会变为0。当然,您可以使用任何变量,而不仅仅是props.rows.length
。
请记住,当这些值更改时,useEffect
(内部数组)上的第二个参数将触发第一个参数上的函数。