页面刷新时React Redux状态丢失

Ami*_*avi 2 reactjs redux react-redux react-router-v4 react-router-dom

在我的React App中,我有3个组件。从第一个组件的按钮开始,我使用链接转到第二个组件。在第二处,我创建了一个状态(redux存储),对其进行了操作,并在完成操作后通过提交按钮将我重定向到第三处。在第三个组件上,我还看到了状态(通过redux chrome工具),但是在这里,当我刷新页面(更改并保存代码时的webpack事情)时,我失去了状态并得到了一个空的Object。

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

index.js

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

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

App.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;
Run Code Online (Sandbox Code Playgroud)

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

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

和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);
Run Code Online (Sandbox Code Playgroud)

最后是我第一次看到状态但在刷新后迷失的Battle组件

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);
Run Code Online (Sandbox Code Playgroud)

Ale*_*nic 8

您可以轻松地将其持久存储在本地存储中。检查以下示例。

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(
  // Other reducer
  persistedState,
);

render(
  <Provider store={store}>
    <App/>
  </Provider>,
  document.getElementById('root');
);
Run Code Online (Sandbox Code Playgroud)

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

例如:

import throttle from 'lodash/throttle';

store.subscribe(throttle(() => {
  saveState(store.getState());
}, 1000));
Run Code Online (Sandbox Code Playgroud)


ill*_*ter 6

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