使用react-hot-loader进行热更新,丢失redux中的状态

问题描述

环境

使用create-react-app --typescript创建项目 版本为3.1.0

问题出现的环境背景及自己尝试过哪些方法

使用react-hot-loader进行热更新,丢失redux中的状态,但是修改代码处热更新成功

复现方法

源码仓库
https://github.com/AfterThree...
npm run start启动 localhost:3000,点击加号按钮使redux中状态更新,然后修改src目录下任何文件,redux状态丢失。
图片描述

相关代码

App.tsx

import { hot } from 'react-hot-loader/root';
import React from 'react';
import { Provider } from 'react-redux';
import configStore from './configStore';
import Test from './Test';

const App: React.FC = () => {
  const store = configStore();
  return (
    <Provider store={store}>
      <Test />
    </Provider>
  );
}

export default hot(App);

configStore.tsx

import { createStore } from 'redux';
import reducers from './reducers';

export default function configStore() {
  const store = createStore(reducers);

  if (module.hot) {
    module.hot.accept('./reducers', () => {
      store.replaceReducer(reducers);
    })
  }

  return store;
}

Test.tsx

...一些导入文件

const Test = () => {
  const dispatch = useDispatch();
  const count = useSelector<IState, number>((state) => state.counter.count);
  const add = () => dispatch({ type: 'add' });
  const minus = () => dispatch({ type: 'minus' });
  return (
    <div>
      <button onClick={add}>+</button>
      <button onClick={minus}>-</button>
      {count}
      update me
    </div>
  );
}

export default Test;

package.json额外依赖

"react-app-rewire-hot-loader": "^2.0.1",
"react-app-rewired": "^2.1.3",
"react-dom": "^16.9.0",
"react-hot-loader": "^4.12.13",

package.json启动脚本修改为

"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-app-rewired eject"
},

你期待的结果是什么?实际看到的错误信息又是什么?

不丢失redux中数据状态,实际丢失了redux中数据状态

阅读 4k
1 个回答

clipboard.png
相当于重新初始化了store

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题