所以我试图访问通常应该已经更新的道具 我可以使用redux devTools查看商店,并且可以确认它已更新。 但是当我在组件中的函数内部时,道具出于某种原因似乎会保持其初始值
const mapStateToProps = ({ repos, page }) => ({
repos,
page // page is 1 then gets updated in the store to 2
});
const mapDispatchToProps = dispatch => {
return {
getData: (page, dateString) => dispatch(getData(page, dateString))
};
};
const ConnectedRepositoryList = ({
alertOnBottom,
page, // after updated in the store the component re-renders and page is 2
getData,
repos
}) => {
const loadRepos = () => {
const date = new Date();
date.setDate(date.getDate() - 30);
const dateString = date.toISOString().split("T")[0];
getData(page, dateString); // here page is still 1 :(
};
useEffect(() => {
loadRepos();
}, []);
const handleOnDocumentBottom = useCallback(() => {
console.log("I am at bottom! ");
loadRepos();
if (alertOnBottom) {
alert('Bottom hit! Too slow? Reduce "debounce" value in props');
}
}, [alertOnBottom]);
return (
my html
);
}
答案 0 :(得分:0)
您的handleOnDocumentBottom
回调依赖于loadRepos
,但是您没有在依赖项数组中包含loadRepos
,因此handleOnDocumentBottom
会被记住并保留其原始值,除非{{1 }} 变化。由于您要在每个渲染上重新声明alertOnBottom
,因此loadRepos
回调将引用handleOnDocument
为loadRepos
时在第一个渲染上定义的page
。您可以将1
添加到loadRepos
的依赖项数组中,但是这种做法违背了handleOnDocumentBottom
的目的,因为useCallback
是每个渲染上的新引用,loadRepos
无论如何都会在每个渲染器上创建。
这里有两个选项可以保留备忘录,但可以纠正行为:
选项1-将handleOnDocumentBottom
添加到依赖项数组。每当page
发生更改时,正确的loadRepos
引用都将在handleOnDocumentBottom
中关闭,但遵循逻辑并意识到page
是{{ 1}}。同样,如果将来page
最终取决于另一个值,则您将需要更新loadRepos
依赖项数组以避免细微的错误:
loadRepos
选项2还将使handleOnDocumentBottom
成为回调,然后将其添加到 const handleOnDocumentBottom = useCallback(() => {
console.log("I am at bottom! ");
loadRepos();
if (alertOnBottom) {
alert('Bottom hit! Too slow? Reduce "debounce" value in props');
}
}, [alertOnBottom, page]); // refresh `handleOnDocumentBottom` whenever page changes
的依赖项数组中:
loadRepos
现在,如果handleOnDocumentBottom
获得任何新的依赖关系或更改,则 const loadRepos = useCallback(() => {
const date = new Date();
date.setDate(date.getDate() - 30);
const dateString = date.toISOString().split("T")[0];
getData(page, dateString); // here page is still 1 :(
}, [page]); // add page as a dependency here
useEffect(() => {
loadRepos();
}, []);
const handleOnDocumentBottom = useCallback(() => {
console.log("I am at bottom! ");
loadRepos();
if (alertOnBottom) {
alert('Bottom hit! Too slow? Reduce "debounce" value in props');
}
}, [alertOnBottom, loadRepos]); // add the memoized loadRepos here
不需要更改,并且依赖关系是明确的。