【发布时间】:2019-02-09 04:22:41
【问题描述】:
在我的反应应用程序中,我有 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")
);
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;
在主页,我有一个链接到 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);
【问题讨论】:
-
这很自然...
-
@BhojendraRauniyar 和解决方案?
-
这里不是 Thunk 作为中间件来处理这个问题吗?如果我想将所有内容持久化到本地存储中,为什么还要使用 redux?
-
否则你可以使用 redux-persist
-
准备初始状态并通过 createStore(combined, { a: 'horse' }) 传递它。 redux.js.org/recipes/structuringreducers/initializingstate。从我的角度来看,这是原因
标签: reactjs redux react-redux react-router-v4 react-router-dom