React Redux 状态在页面刷新时丢失

新手上路,请多包涵

在我的反应应用程序中,我有 3 个组件。通过一个按钮从第一个组件,我使用链接转到第二个组件。在第 2 次我创建一个状态(redux 存储),对其进行操作,当通过提交按钮完成操作时,我重定向到第 3 个组件。在第三个组件,我也看到了状态(通过 redux chrome 工具),但是当我刷新页面时(更改和保存代码时的 webpack 事情),我失去了状态并得到一个空对象。

这是我的应用程序的结构。

index.js

 const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <Route component={App} />
    </Provider>
  </BrowserRouter>,
  document.getElementById("root")
);

应用程序.js

 const App = ({ location }) => (
  <Container>
    <Route location={location} path="/" exact component={HomePage} />
    <Route location={location} path="/GameInit" exact component={GameInit} />
    <Route location={location} path="/Battle" exact component={Battle} />
  </Container>
);

App.propTypes = {
  location: PropTypes.shape({
    pathname: PropTypes.string.isRequired
  }).isRequired
};

export default App;

在主页上,我有一个链接到 GameInit 的按钮

const HomePage = () => (<Button color="blue" as={Link} to="/GameInit">START GAME</Button>);
export default HomePage;

GameInit 页面看起来像

class GameInit extends Component {
  componentWillMount() {
    const { createNewPlayer} = this.props;
    createNewPlayer();
  }
/* state manipulation till it gets valid */
 palyerIsReady()=>{ history.push("/Battle");}

export default connect(mapStateToProps,{ createNewPlayer})(GameInit);

最后是我第一次看到状态但在刷新时丢失的战斗组件

class Battle extends Component {
  render() {return (/*some stuff*/);}}

Battle.propTypes = {
  players: PropTypes.object.isRequired // eslint-disable-line
};
const mapStateToProps = state => ({
  players: state.players
});
export default connect(mapStateToProps,null)(Battle);

原文由 Amir-Mousavi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

您可以轻松地将其保存在本地存储中。检查下面的示例。

 const loadState = () => {
  try {
    const serializedState = localStorage.getItem('state');
    if(serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (e) {
    return undefined;
  }
};

const saveState = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('state', serializedState);
  } catch (e) {
    // Ignore write errors;
  }
};

const peristedState = loadState();

store.subscribe(() => {
  saveState(store.getState());
});

const store = createStore(
  persistedState,
  // Others reducers...
);

render(
  <Provider store={store}>
    <App/>
  </Provider>,
  document.getElementById('root');
);


序列化是一项昂贵的操作。您应该使用限制功能(如 lodash 实现的功能)来限制保存次数。

例如:

 import throttle from 'lodash/throttle';

store.subscribe(throttle(() => {
  saveState(store.getState());
}, 1000));

原文由 Alexandre Annic 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 redux-persist 之类的东西将 redux 状态保存到 local storage 或另一个存储系统。

原文由 illiteratewriter 发布,翻译遵循 CC BY-SA 4.0 许可协议

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