redux - 如何在 getInitialProps 中使用 redux 钩子
问题描述
我一直在尝试通过重新加载来坚持我的 redux 商店。我最初使用 useEffect 来调度我的操作,但是当我尝试重新加载页面路由器时,它变得未定义,并且出现 500 错误。之后我尝试使用 getInitialProps 并使用 ctx.query.id 但我遇到了另一个错误,说只能在函数组件的主体内部调用挂钩。
如何让它在 getInitialProps 内部工作,以及通过重新加载持久保存我的商店数据的最佳方式是什么?
export default function CarPage() {
const dispatch = useDispatch()
const router = useRouter()
const car = useSelector((state) => state.cars.car)
/*
useEffect(() => {
if(!car && router) {
dispatch(getCar(router.query.id))
}
}, [])
*/
return (
<Container>
<h2>{car.model}</h2>
</Container>
)
}
CarPage.getInitialProps = async (ctx) => {
const dispatch = useDispatch()
dispatch(getCar(ctx.query.id))
}
解决方案
要通过页面重新加载来持久化 redux 存储,我们肯定需要使用浏览器存储。我建议使用https://github.com/rt2zz/redux-persist。
要使用dispatch
inside getInitialProps
,请尝试使用此代码片段而不是使用useDispatch()
钩子。
CarPage.getInitialProps = async ({ store, query }) => {
store.dispatch(getCar(query.id));
return { initialState: store.getState() };
}
推荐阅读
- asp.net - 当前上下文中不存在名称“配置”
- python - Discord.py:我如何让机器人获取在给定时间内对消息做出反应的用户列表
- python - 如何调整条形图的图形间距。Matplotlib
- wordpress - Nginx 反向代理在 Docker 上深度链接 Wordpress
- ruby-on-rails - 用devise使用cancancan时,是否需要将devise添加到capability.rb中?
- php - 在 Yii2 高级(php 框架)中设置“请求 baseUrl”后无法设置“AppAsset baseurl”
- html - 对齐所有按钮正确位置的问题
- discord.py - discord.py 前缀命令
- javascript - 访问对象数组中的值“firstName”
- python - mod_wsgi 在 Django 和 venv 上存在问题。无法作为 python 模块加载。ModuleNotFoundError:没有名为“django”的模块