【问题标题】:Access store in getInitialProps with redux persist in nextjs使用 redux 访问 getInitialProps 中的存储在 nextjs 中持续存在
【发布时间】:2020-10-04 13:10:40
【问题描述】:

我正在使用此处的 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;

我可以看到,在 getInitialProps 中的两次调度调用(刷新页面时)从日志语句的输出[计数打印为 2] 中更新了存储。但是,Count: &lt;span&gt;{counter}&lt;/span&gt; 行上的 counter 变量中的存储没有更新,它仍然显示0。如果按钮用于递增,则它可以与 redux persist 一起正常工作。

所以我的问题是,我如何访问商店并从 getInitialProps 更新状态?假设 counter 目前的值为 5,当页面刷新时,因为我使用 redux persist,它的值仍然是 5。但是如果我要在 getInitialProps 中调度一个动作并且页面被刷新,它不应该调用 getInitialProps 并将计数器值更新为 6 吗?

编辑:['err', 'req', 'res', 'pathname', 'query', 'asPath', 'AppTree'] 这是我在 getInitialProps 中执行console.log(Object.keys(ctx)); 时得到的输出

【问题讨论】:

  • 我遇到了同样的问题。你找到解决方法了吗?

标签: javascript reactjs redux next.js


【解决方案1】:

不要在getInitialProps 中初始化存储。要访问商店,您只需检查:

static async getInitialProps(context) {
    console.log(context.ctx); // one of the property is 'store'
    return {};
  }

【讨论】:

  • [ 'err', 'req', 'res', 'pathname', 'query', 'asPath', 'AppTree' ] 这是我在 getInitialProps 中执行console.log(Object.keys(ctx)); 时得到的输出。我已经用同样的方法更新了这个问题。没有store 属性。这是我克隆的项目github.com/vercel/next.js/tree/master/examples/…
猜你喜欢
  • 2020-10-30
  • 2018-01-05
  • 2018-05-05
  • 1970-01-01
  • 2020-11-26
  • 2017-10-12
  • 2021-03-17
  • 2018-06-19
  • 1970-01-01
相关资源
最近更新 更多