在呈现表之前,我正在尝试刷新redux存储中的数据。我调用useEffect进行刷新,希望useSelector在返回对rest服务的调用时得到更新。我正在将数据馈送到react表的useTable钩子。当我添加对useEffect的调用时,我会对页面进行无限刷新,一遍又一遍地对数据调用useSelector,但我不明白为什么。有人能给我指正确的方向吗?
这是我的组件,redux状态函数工作正常。我在这里不显示实际的表,只是显示对useTable钩子的调用。
function RecurringPublicationTable(props) {
const dispatch = useDispatch();
// This will get called one time to refresh the recurring publishing data
useEffect(() => {
console.log("UseEffect");
dispatch(getRecurringJobs());
}, []);
// This should get the data from store and subscribe.
const data = useSelector((state) => {
console.log("UseSelector");
return state.recurringPublisher.recurringPublishJobs;
});
const columns = [
{
Header: "Name",
accessor: "recurringJobName",
},
{
Header: "Publish Location",
accessor: "publishLocation",
},
];
// This should get the data ready for the table, but fails with max depth exceeded
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
useTable({
columns,
data,
});
return <div>Hello Ken</div>;
}
export default RecurringPublicationTable;
我尝试了这些建议,但通过不断的重新渲染,结果仍然是一样的。
我发现,我可以在渲染表之前刷新数据,方法是将表移动到一个组件,然后让另一个组件执行useEffect,然后在效果完成时渲染表组件。我也不确定为什么列或数据需要useMemo。我看到了文档,但它似乎在没有包装的情况下工作。
const RecurringPublicationTableContainer = (props) => {
const dispatch = useDispatch();
const isLoading = useSelector((state) => {
console.log("The state is:", state);
return state.recurringPublisher.isrecurringPublishJobsLoading;
});
console.log("Are we loading?:",isLoading);
// This will get called one time to refresh the recurring publishing data
useEffect(() => {
console.log("UseEffect");
dispatch(getRecurringJobs());
}, []);
return isLoading ? <p>Loading...</p> : <RecurringPublicationTable />;
};
export default RecurringPublicationTableContainer;
然后RecurringPublicationTable组件变为
function RecurringPublicationTable(props) {
const dispatch = useDispatch();
const data = useSelector((state) => {
console.log("The state is:", state);
return state.recurringPublisher.recurringPublishJobs;
});
const columns = [
{
Header: "Name",
accessor: "recurringJobName",
},
{
Header: "Publish Location",
accessor: "publishLocation",
},
];
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
useTable(
{
columns,
data,
},
useFilters,
useSortBy
);