在我的反应应用程序中,我有 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 许可协议
您可以轻松地将其保存在本地存储中。检查下面的示例。
序列化是一项昂贵的操作。您应该使用限制功能(如
lodash
实现的功能)来限制保存次数。例如: