Redux状态不会通过操作调度进行更新

时间:2017-01-05 00:27:06

标签: reactjs redux react-router react-redux react-router-redux

我已经查看了用于使用redux和react-router构建反应应用程序的每个文档和示例项目,但我似乎无法弄清楚如何获得我的redux状态我发送动作时更新。正如您在此屏幕截图中看到的那样,操作正确调度,但我的store / nextState没有更新。

enter image description here

ACTION:

export function updateUsername(username) {
  return { type: types.UPDATE_USERNAME, username };
}

REDUCER(编辑:我已尝试过这两种变体):

   /* first variation */
   const username = (
      state = '',
      action,
    ) => {
      switch (action.type) {
        case types.UPDATE_USERNAME:
          return Object.assign({}, state, {
            username: action.username,
          });
        default:
          return state;
      }
    };

  /* second variation */
  const username = (
    state = '',
    action,
  ) => {
    switch (action.type) {
      case types.UPDATE_USERNAME:
        return action.username;
      default:
        return state;
    }
  };

REDUCER COMBINATION:

const user = combineReducers({
  isAuthenticated,
  token,
  password,
  username,
});

export default user;

REDUCERS / INDEX.JS:

const rootReducer = combineReducers({
  isFetching,
  open,
  search,
  user,
  routing: routerReducer,
});

export default rootReducer;

商店配置:

import React from 'react';
import { createStore, compose, applyMiddleware } from 'redux';
import createLogger from 'redux-logger';
import thunkMiddleware from 'redux-thunk';
import { routerMiddleware } from 'react-router-redux';
import rootReducer from '../reducers';
import * as actions from '../actions';

function configureStore(history, initialState) {
  const loggerMiddleware = createLogger();

  const enhancer = window.__REDUX_DEVTOOLS_EXTENSION__ &&
    window.__REDUX_DEVTOOLS_EXTENSION__();

  const store = createStore(
    rootReducer,
    initialState,
    compose(
      applyMiddleware(
        thunkMiddleware,
        loggerMiddleware,
        routerMiddleware(history),
      ),
      enhancer,
    ),
  );

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextReducer = rootReducer;
      store.replaceReducer(nextReducer);
    });
  }

  return store;
}

export default configureStore;

存储创建:

const initialState = {};

const store = configureStore(browserHistory, initialState);
const history = syncHistoryWithStore(browserHistory, store);
const routes = createRoutes(store);


render(
  <Provider store={store}>
      <Router history={history} routes={routes} />
  </Provider>,
  document.getElementById('root'),
);

最后,组件:

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import TextField from 'material-ui/TextField';
import validator from 'validator';
import className from 'classnames';
import { Link } from 'react-router';
import * as AuthActions from '../../actions/AuthActions';

class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleUsernameChange(e) {
    this.props.actions.updateUsername(validator.escape(e.target.value.trim()));
  }

  handlePasswordChange(e) {
    this.props.actions.updatePassword(validator.escape(e.target.value.trim()));
  }

  handleSubmit(e, getState) {
    e.prevent.default();
    const user = { username: this.props.user.username, password: this.props.user.password };
    console.log(user);
    this.props.actions.loginUser(user);
  }

  render() {
    return (
          <form autoComplete="off" onSubmit={this.handleSubmit} className='login-form'>
            <TextField
              type="username"
              autoFocus="true"
              floatingLabelText="Username"
              floatingLabelFixed={true}
              autoComplete="off"
              onChange={this.handleUsernameChange}
              />
            <br/>
            <TextField
              type="password"
              autoFocus="true"
              floatingLabelText="Password"
              floatingLabelFixed={true}
              autoComplete="off"
              onChange={this.handlePasswordChange}
              />
          </form>
    );
  }
}

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

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(AuthActions, dispatch),
  };
}


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

我已经坚持了一个星期了,所以你能提供的任何帮助都会非常感激!谢谢!

1 个答案:

答案 0 :(得分:1)

我没有运行你的代码,所以我不能随便说这是否会修复它,但你的用户名reducer返回一个具有username属性的对象,当它应该返回{{ 1}}字符串。

action.username

另外,您是否确认您的const username = (state = '', action) => { switch (action.type) { case types.UPDATE_USERNAME: return action.username default: return state; } }; 声明中没有拼写错误?我在您的reducer中看到您引用了types,但在您的动作创建器中,您使用字符串types.UPDATE_USERNAME设置了类型。