简体   繁体   English

React&Redux-路由更改后状态变空

[英]React & Redux - state getting empty after route changed

I'm building a react & redux application and the problem I'm having is that after I do browserHistory.push('/myroute') and being successfully routed, I see that my state has been cleared, and while I need some data that's on the state from the previous route.. I still haven't found out if this is natural or not 我正在构建一个React&Redux应用程序,遇到的问题是在执行browserHistory.push('/myroute')并成功路由之后,我发现状态已清除,并且需要一些数据那是上一条路线的状态。.我仍然没有发现这是否自然

My case is that I need to transfer data between routes.. I thought that is what state is for 我的情况是我需要在路由之间传输数据。我认为那是什么状态

this is my log: 这是我的日志:

 action @ 16:21:35.917 ON_ACTIVATE_FINISHED
counter.js:68 Object {counter: Object, registerReducer: Object, routing: Object}
core.js:97  action @ 16:21:35.928 @@router/LOCATION_CHANGE
register.js:9 Object {}
core.js:97  action @ 16:21:38.840 INPUT_PW_CHANGED

routes.js : routes.js

// @flow
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App';
import HomePage from './containers/HomePage';
import CounterPage from './containers/CounterPage';
import RegisterPage from './containers/RegisterPage';


export default (
  <Route path="/" component={App}>
    <IndexRoute component={CounterPage} />
    <Route path="/counter" component={CounterPage} />
    <Route path="/home" component={HomePage} />
    <Route path="/register" component={RegisterPage} />
  </Route>
);

CounterPage.js : CounterPage.js

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/counter';

function mapStateToProps(state) {
  return {
    counter: state.counter,
    key: state.key
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(CounterActions, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

RegisterPage.js : RegisterPage.js

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Register from '../components/Register';
import * as RegisterActions from '../actions/register';

function mapStateToProps(state) {
  return {
    pw: state.pw
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(RegisterActions, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Register);

reducers/counter.js : reducers/counter.js

import { Router, hashHistory } from 'react-router';
export const INPUT_KEY_CHANGED = 'INPUT_KEY_CHANGED';
export const ACTIVATE_KEY = 'ACTIVATE_KEY';
export const ON_ACTIVATE_FINISHED = 'ON_ACTIVATE_FINISHED';

export function onInputChanged(e) {
    return {
        type: INPUT_KEY_CHANGED,
        data: e.target.value
    };
}

export function activate() {
    return {
        type: ACTIVATE_KEY
    };
}

export function onActivateFinished(json) {
    return {
        type: ON_ACTIVATE_FINISHED,
        json
    }
}

const SERVER_ADDRESS = 'http://*******:9001';
export const fetchActivationKey = () => (dispatch, getState) => {
    var request = require('request-promise');

    dispatch(activate())
    const key = getState().counter.key;
    return request(`${SERVER_ADDRESS}/invite/${key}`)
        .then((fHost) => {
            return request(`http://${fHost}:9000/api/start/${key}`)
        })
        .then(json => {
            dispatch(onActivateFinished(json))
            let currentState = getState();
            if (currentState.counter.model.status === 0) {
                hashHistory.push('/register');
            }
        });
}

Any ideas? 有任何想法吗?

Based on https://github.com/reactjs/react-redux/blob/master/docs/api.md#provider-store and on my own app, it should look like this: 基于https://github.com/reactjs/react-redux/blob/master/docs/api.md#provider-store和我自己的应用程序,它应如下所示:

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={App}>
        <Route path="foo" component={Foo}/>
        <Route path="bar" component={Bar}/>
      </Route>
    </Router>
  </Provider>,
  document.getElementById('root')
)

But I don't see the Provider and the Router in your code, the Provider is here to pass the main state to all components and without it I'm not sure it would work properly. 但是我在您的代码中看不到ProviderRouterProvider在这里是将主要状态传递给所有组件的信息,如果没有它,我不确定它是否可以正常工作。

Normally, you can't use connect() without wrapping the root component in Provider . 通常,如果不connect()根组件包装在Provider ,则无法使用connect()

Let's have a try at this. 让我们尝试一下。

Take this code 拿这个代码

.then(json => {
  dispatch(onActivateFinished(json))
  let currentState = getState();
  if (currentState.counter.model.status === 0) {
    hashHistory.push('/register');
  }
});

and change it to this: 并将其更改为:

.then(json => {
  dispatch(onActivateFinished(json))
  let currentState = getState();
  this.setState({counter: currentState.counter});
  if (currentState.counter.model.status === 0) {
    hashHistory.push('/register');
  }
});

I'm still learning React and by no means am any kind of expert. 我仍在学习React,绝不是任何专家。 So I am not 100% certain this will work. 所以我不是100%肯定这会起作用。 But it is an effort to assist based off of what I currently know. 但这是根据我目前所知道的情况提供的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM