我想使用UseState钩子来更新Table
组件中的数据。要在Table
组件中使用的数据由paginationForDataAdded
导入的另一个函数获取。
由于重新渲染,它看起来像堆栈溢出。setAllData(searchResults);
将重新渲染组件,并再次进行 API 调用和重新处理。
调用 API 的正确方法。
const [allData, setAllData] = useState([]);
useEffect(function () {
const {
searchResults,
furnishedData,
entitledData
} = paginationForDataAdded({
searchFunction: search,
collectionsData: collections
});
setAllData(searchResults);
});
假设paginationForDataAdded
是一个返回Promise
的函数,该使用如下所示的对象进行解析:
{
searchResults: { resultarray: [...] },
furnishedData: [...],
entitledData: [...]
}
您应该在 in 组件中执行以下操作:
function App(props) {
const [allData, setAllData] = React.useState([]);
// ...
React.useEffect(() => {
paginationForDataAdded({
searchFunction: search,
collectionsData: collections,
})
.then(
({ searchResults, furnishedData, entitledData }) => {
const nextAllData = searchResults.resultarray || [];
setAllData(nextAllData);
}
)
.catch(/* handle errors appropriately */);
// an empty dependency array so that this hooks runs
// only once when the component renders for the first time
}, [])
return (
<Table
id="pop-table"
data={allData}
tableColumns={[...]}
/>
);
}
但是,如果paginationForDataAdded
不是异步调用,则应执行以下操作:
function App(props) {
const [allData, setAllData] = React.useState([]);
// ...
React.useEffect(() => {
const {
searchResults,
furnishedData,
entitledData,
} = paginationForDataAdded({
searchFunction: search,
collectionsData: collections
});
const nextAllData = searchResults.resultarray || [];
setAllData(nextAllData)
// an empty dependency array so that this hooks runs
// only once when the component renders for the first time
}, [])
return (
<Table
id="pop-table"
data={allData}
tableColumns={[...]}
/>
);
}
希望这有帮助。