【发布时间】:2019-11-27 15:07:14
【问题描述】:
编辑:已解决!请参阅below。
我希望我的 Blog 组件在每次浏览器请求其 URL 时触发 fetchBlog 动作创建者,无论是通过链接还是刷新。我想用 React useEffect Hook 和 React-Redux useDispatch 和 useSelector Hooks 来做。但是,我的操作仅在点击页面链接时触发;我不明白为什么,即使在阅读了几个解释(如the official docs)之后。
代码如下:
// 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。
【问题讨论】:
-
组件是否已卸载,也许这就是它之后不触发的原因?
-
我认为它没有被卸载,因为我仍然得到一个错误:动作没有触发,所以
state.blogs是一个空数组,所以data是未定义的,所以阅读@ JSX 部分中的 987654339@ 会抛出TypeError: Cannot read property 'title' of undefined。但我对此不是很有信心 - 我怎么能 100% 肯定组件已卸载?什么可以卸载它?
标签: javascript reactjs react-redux react-hooks