[英]How to change the value of rowData state in react hook
索引.tsx
const [activeTab, setActiveTab] = useState({ active: 'customers' });
const [rowData, setRowData] = useState([]);
const handleChangeTab = (activeKey) => {
setActiveTab({ active: activeKey });
}
useEffect(() => {
if (activeTab.active === 'customers') {
setRowData([
{
customId: 1,
name: "Customer 1",
},
{
customId: 2,
name: "Customer 2",
}
])
} else {
setRowData([
{
customId: 1,
name: "Supplier 1",
},
{
customId: 2,
name: "Supplier 2",
}
])
}
}, []);
return({
<div>
<Nav appearance="tabs" activeKey={activeTab.active} onSelect={handleChangeTab} justified>
<Nav.Item eventKey="customers" icon={<Icon icon='group' />}>
Customers
</Nav.Item>
<Nav.Item eventKey="suppliers" icon={<Icon icon='truck' />}>
Suppliers
</Nav.Item>
</Nav>
{rowData && rowData.map((item, index) => (
<div key={index}>
<label>{index}</label>
<span>ID: {item.customId}</span>< br/>
<span>Name: {item.name}</span><br/></br>
</div>
)}
</div>
})
当我尝试更改选项卡时遇到问题,它不会更改 setRowData 的值。 我已经添加了这个:
useEffect((), => { .... }, [rowData]);
但它会导致无限循环。
每次更改选项卡时如何更改 rowData 的值? 没有无限循环? 它还应该改变 rowData 的值
useEffect 使用是正确的,但是依赖是错误的。 您应该放入依赖数组中的是触发效果的值。 在这种情况下, activeTab.active
,所以它将是useEffect(() =>..., [activeTab.active]);
因此,当您更改选项卡时,会触发效果。
const rowData =
activeTab.active === 'customers'
? [
{
customId: 1,
name: 'Customer 1',
},
{
customId: 2,
name: 'Customer 2',
},
]
: [
{
customId: 1,
name: 'Supplier 1',
},
{
customId: 2,
name: 'Supplier 2',
},
];
根据 activeTab.active 指定 rowData
更新:
您可以使用 useMemo 进行优化
const rowData = React.useMemo(
() =>
activeTab.active === 'customers'
? [
{
customId: 1,
name: 'Customer 1',
},
{
customId: 2,
name: 'Customer 2',
},
]
: [
{
customId: 1,
name: 'Supplier 1',
},
{
customId: 2,
name: 'Supplier 2',
},
],
[activeTab.active]
);
您在useEffect
中指定了错误的依赖项。 您需要指定依赖activeTab.active
以便正确触发。 你的 useEffect 应该是useEffect(() => { // your logic here }, [activeTab.active]
或者您可以在handleChangeTab
function 本身中设置 rowData。
const handleChangeTab = (activeKey) => {
setActiveTab({ active: activeKey });
if (activeKey === 'customers') {
setRowData([
{
customId: 1,
name: "Customer 1",
},
{
customId: 2,
name: "Customer 2",
}
])
} else {
setRowData([
{
customId: 1,
name: "Supplier 1",
},
{
customId: 2,
name: "Supplier 2",
}
])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.