![](/img/trans.png)
[英]Why is this action.type not firing in the Reducer of my React/Redux App?
[英]Using React and Redux Hooks, why is my action not firing?
編輯:已解決! 請看下面。
我希望我的Blog
組件在每次瀏覽器請求其 URL 時觸發fetchBlog
操作創建者,無論是通過鏈接還是刷新。 我想使用 React useEffect
Hook 以及 React-Redux useDispatch
和useSelector
Hook 來完成。 但是,我的操作僅在點擊頁面鏈接時才會觸發; 我不明白為什么,即使在閱讀了幾個解釋(如官方文檔)之后也是如此。
這是代碼:
// 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
with mapStateToProps
和mapDispatchToProps
會產生相同的結果。 問題似乎出在useEffect
。
我認為問題是你正在返回調度呼叫。 從 useEffect 返回的函數是清理函數,所以我認為這不會在掛載或更新時運行——僅在卸載之前。 試試這個:
export default function Blog() {
// ...
// Don't return from useEffect. Just call dispatch within the body.
useEffect(() => {
dispatch(fetchBlog(slug);
}, [slug, dispatch]);
// ...
}
https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect
我想澄清問題是什么,@Trace 引導我找到了這個問題。
useEffect
沒有在刷新時被調用,因為它是在組件呈現/返回之后被調用的。 刷新時,狀態——包括博客數據——丟失; 沒有返回,而是TypeError
因為data.title
不存在。 所以useEffect
永遠不會有機會被調用並獲取博客的內容。
解決方案是這樣的:
export default function Blog() {
// ...
useEffect(/* ... */)
const blog = useSelector((state) => state.blogs[0]);
if (!blog) {
return <p>Loading...</p>
}
// return actual blog contents here
}
所以現在fetchBlog
確實被調用,更新blog
並呈現內容。
我不清楚鼻涕蟲是從哪里來的。
理論上useEffect
在每次渲染后運行。 在多個參數的情況下,當第二個參數中傳遞的數組參數之一發生變化時,它將運行回調。
創建一個帶有空數組的useEffect
作為第二個參數以運行它“一次”(例如,當您刷新時)或檢查 slug 值。
檢查回購后編輯:
您可以使用match
從 react-router 獲取 slug,這對您來說可能很方便。
export default function Blog({ match }) { const slug = match.params.slug; etc
git repo 顯示了如何將 dispatch as 作為數組參數添加到useEffect
中,這不是必需的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.