React-Redux:松散状态

时间:2017-05-31 10:43:09

标签: javascript reactjs react-redux apollo

所以,我遇到的问题是redux没有保持'token'值的状态。 在查看应用程序后,您将被引导至登录页面。提交您的登录详细信息会返回一个身份验证令牌,该令牌会将返回的令牌值的值分配给变量令牌,将令牌添加到道具,然后将您重定向到应用程序的主要部分'/'。

如果我立即返回登录页面'/ login',则令牌将从道具中消失,导致用户必须再次重新登录。

这里有什么问题?

app.js

render(
  <ApolloProvider store={store} client={client}>
    { /* Tell the Router to use our enhanced history */ }
    <Router history={history}>
      <Route path="/" component={App}>
        <IndexRoute component={PhotoGrid} />
        <Route path="/view/:postId" component={Single}></Route>
        <Route path="/login" component={LoginUser}></Route>
      </Route>
    </Router>
  </ApolloProvider>,
  document.getElementById('root')
);

App.js

function mapStateToProps(state) {
   return {
    token: state.token[0]
  };
}

Root reducer(index.js)

import { combineReducers } from 'redux';
import client from '../apolloClient';
import { routerReducer } from 'react-router-redux'; // we need this for react-router
import tokenDetails from './tokenDetails';
const rootReducer = combineReducers({
  token: tokenDetails,
  routing: routerReducer,
  apollo: client.reducer(),
});

export default rootReducer;

tokenDetails.js

var tokenDetails = function(state, action) {

  if (state === undefined) {
    state = [];
  }

  switch (action.type) {
    case 'Graphcool_Token':
      const newState = [action.payload];
      return newState;
    default:
      return state;
  }
}

export default tokenDetails;

actionCreator,JS

export function authToken(token) {
  return (dispatch) => {
    dispatch({
      type: 'Graphcool_Token',
      payload: token
    });
  } 
}

LoginUser.js

  signinUser: function(emailID, passwordID) {

    const email = emailID;
    const password = passwordID;

    this.props.client.mutate({
      mutation: signinUser_Mutation,
      variables: {
        email,
        password,
      },
      options: {
        cachePolicy: 'offline-critical', 
        fetchPolicy: 'cache-first',
      },
    })
    .then(this.updateStateLoginDetails)
    .catch(this.handleSubmitError);
  },

  updateStateLoginDetails: function({data}) {
    this.props.authToken(data.signinUser.token);
    this.context.router.push('/');
  },

  handleSubmitError: function(err) {
    console.error(err.message);
  },

  handleSubmit: function(e) {
    e.preventDefault();
    this.signinUser(this.refs.email.value, this.refs.password.value);
    this.refs.loginForm.reset();
    this.refs.email.focus();
  },
  render: function() {
  }

store.js

const middlewares = [thunk, client.middleware()];

const enhancers = compose(
    applyMiddleware(...middlewares),

    (typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined' || process.env.NODE_ENV !== 'production') ? window.__REDUX_DEVTOOLS_EXTENSION__() : (f) => f,
    autoRehydrate(),
);

const store = createStore(
  rootReducer,
  {}, // initial state
  enhancers
);

// begin periodically persisting the store
persistStore(store, {storage: localForage});

export const history = syncHistoryWithStore(
  browserHistory, 
  store
);

if(module.hot) {
  module.hot.accept('./reducers/', () => {
    const nextRootReducer = require('./reducers/index').default;
    store.replaceReducer(nextRootReducer);
  });
}

export default store;

0 个答案:

没有答案