编辑:解决了!请看下面。
我希望我的Blog
组件fetchBlog
在浏览器每次通过链接或刷新请求其URL时触发动作创建者。我想使用React useEffect
Hook以及React-ReduxuseDispatch
和useSelector
Hooks来做到这一点。但是,只有在单击该页面的链接时,我的操作才会触发;我什至不明白为什么,即使在阅读了几种解释之后(例如官方文档)。
这是代码:
// Everything duly imported, or else VSC would yell at me
export default function Blog() {
const dispatch = useDispatch();
// slug is set here with useSelector, this always works
useEffect(() => {
dispatch(fetchBlog(slug))
}, [slug, dispatch]);
const blog = useSelector((state) => state.blogs[0]);
// return renders the blog information from the blog constant
// since the action does not fire, blog is undefined because state.blogs is an empty array
}
我知道,fetchBlog
由于Redux DevTools以及我在那放置了刷新,刷新后不会触发debugger
。(并且后端日志不显示请求传入。)动作创建者本身和减速器必须正在工作;如果不是,则通过链接访问该页面时将无法正确加载该页面。
编辑:我已经决定useSelector
和useDispatch
都不是问题的根源,如改变使用代码connect
与mapStateToProps
和mapDispatchToProps
给出了相同的结果。问题似乎在useEffect
。
我不清楚me从何而来。
理论上讲useEffect
,每次渲染后都会运行一次。如果有多个参数,则当第二个参数中传递的数组参数之一更改时,它将运行回调。
创建一个useEffect
带有空数组的数组作为第二个参数以“一次”运行它(例如,刷新时),或者检查段塞值。
检查仓库后进行编辑:
您可以使用来从react-router获取该信息match
,这可能对您来说很方便。
export default function Blog({ match }) {
const slug = match.params.slug;
etc
git repo显示了如何将dispatch as作为数组参数添加到useEffect
,这是不必要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句