[英]Access store in getInitialProps with redux persist in nextjs
我在這里使用 nextjs 示例: https://github.com/vercel/next.js/tree/canary/examples/with-redux-persist 。 我修改了 pages/index.js 如下:
const Index = () => {
const counter = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<h1>
Count: <span>{counter}</span>
</h1>
<button onClick={() => dispatch(incrementCount())}>+1</button>
<button onClick={() => dispatch(decrementCount())}>-1</button>
<button onClick={() => dispatch(resetCount())}>Reset</button>
</div>
);
};
Index.getInitialProps = (ctx) => {
const store = initializeStore();
store.dispatch(incrementCount());
store.dispatch(incrementCount());
console.log(Object.keys(ctx));
console.log("store", store.getState());
return {};
};
export default Index;
我可以看到,在來自日志語句的 output 的 getInitialProps 中的兩個調度調用(刷新頁面時)之后,商店已更新[計數打印為 2]。 但是,商店在Count: <span>{counter}</span>
行的counter
變量中沒有更新,它仍然顯示0
。 如果按鈕用於增加它與 redux 一起工作正常。
所以我的問題是,我如何訪問商店並從 getInitialProps 更新 state? 假設計數器此刻的值為 5,當頁面刷新時,因為我使用的是 redux persist,它的值仍然是 5。但是如果我要在 getInitialProps 中調度一個動作並且頁面被刷新,它不應該調用 getInitialProps 並將計數器值更新為 6 嗎?
編輯: ['err', 'req', 'res', 'pathname', 'query', 'asPath', 'AppTree']
這是我在執行console.log(Object.keys(ctx));
時得到的 output console.log(Object.keys(ctx));
在 getInitialProps 里面
不要在getInitialProps
中初始化存儲。 要訪問商店,您只需檢查:
static async getInitialProps(context) {
console.log(context.ctx); // one of the property is 'store'
return {};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.