Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Redux reducer将新对象添加到数组_Arrays_Reactjs_Object_Redux_Reducers - Fatal编程技术网

Arrays Redux reducer将新对象添加到数组

Arrays Redux reducer将新对象添加到数组,arrays,reactjs,object,redux,reducers,Arrays,Reactjs,Object,Redux,Reducers,我在提交后通过调度操作向对象数组添加新对象时遇到问题。这样做的目的是在整个站点上显示flash消息。我有两个组件负责显示消息,FlashMessagesList和FlashMessage。服务器还使用消息对象进行响应,该对象需要添加到消息数组中。问题是,当动作被调度时,我可以看到它在redux devtools中被调度,但状态从未改变,我所做的一切都没有改变,它仍然是空数组,我对此非常困惑,所以欢迎提供任何建议。以下是相关代码: /*flashMessagesList组件*/ import Re

我在提交后通过调度操作向对象数组添加新对象时遇到问题。这样做的目的是在整个站点上显示flash消息。我有两个组件负责显示消息,FlashMessagesList和FlashMessage。服务器还使用消息对象进行响应,该对象需要添加到消息数组中。问题是,当动作被调度时,我可以看到它在redux devtools中被调度,但状态从未改变,我所做的一切都没有改变,它仍然是空数组,我对此非常困惑,所以欢迎提供任何建议。以下是相关代码:

/*flashMessagesList组件*/

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import FlashMessage from './FlashMessage';
import { deleteFlashMessage } from '../../actions/actionFlashMessage';

class FlashMessagesList extends Component { //this is conected component cause we need data from store
  render() {
    const messages = this.props.messages.map(message =>
    <FlashMessage key={message.id} message={message} deleteFlashMessage={this.props.deleteFlashMessage}/>
  );
  return (
    <div>{messages}</div>
    );
  }
}
function mapStateToProps(state) {
  return { //here we take a slice of global state
    messages: state.flash.messages //define this in root reducer
  };
}
function mapDispatchToProps(dispatch) {
  return {
    deleteFlashMessage: () => dispatch(deleteFlashMessage())
  };
}
FlashMessagesList.propTypes = { //what this component will take
  messages: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string.isRequired,
      style: PropTypes.string.isRequired,
      text: PropTypes.string.isRequired
    })
  ),
  deleteFlashMessage: PropTypes.func.isRequired
};
export default connect(mapStateToProps, mapDispatchToProps)(FlashMessagesList); //pass message from store to this component
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';

class FlashMessage extends Component {

  deleteFlashMessage = () =>{
    this.props.deleteFlashMessage(this.props.message.id); //dispatch some action that it has on it props
  }
  render() {
    const { id, style, text } = this.props.message; //we can deconstruct message cause it is object
    return (
    <div className={classnames('alert', {
      'alert-success': style === 'success',
      'alert-danger': style === 'danger'
    })}
    >
    { text }
    <button className="close" onClick={this.deleteFlashMessage}><span>&times;</span></button>
    </div>
    );
  }
}
FlashMessage.propTypes = {
  message: PropTypes.object.isRequired,
  deleteFlashMessage: PropTypes.func.isRequired
};
export default FlashMessage;
/*actionflashMessage*/

import * as types from '../actions/actionTypes';
import deepFreeze from 'deep-freeze';
import expect from 'expect';

const INITIAL_STATE = {
    messages: []
};
const reducerFlashMessage = (state = INITIAL_STATE, action) => {
    switch (action.types) {
        case types.ADD_FLASH_MESSAGE:
            return { ...state,
                messages: [ ...state.messages, {
                    id: action.message.id,
                    style: action.message.style,
                    text: action.message.text
                }]
            };
    }
    return state;
};

export default reducerFlashMessage;
import * as types from './actionTypes';

export function addFlashMessage(message) {
      return {
        type: types.ADD_FLASH_MESSAGE,
        message

      };
    }
export function registerUser({
  timezone,
  name,
  email,
  password,
  passwordConfirmation
}) {
  return dispatch => {
    dispatch(isLoading(true));
    axios.post('/auth/signup', {
      timezone,
      name,
      email,
      password,
      passwordConfirmation
    })
    .then(response => {
      dispatch(_registerUserSuccess(response.data.errors, response.data.message));
      dispatch(isLoading(false));
      dispatch(addFlashMessage(response.data.message));
      dispatch(formReset());
      // browserHistory.push('/signin');
      setTimeout(() => {
              // dispatch(_hideNotifications());
      }, 2000);
      // document.getElementById('form').reset();
    })
    .catch(error => {
      if (error.response) {
        dispatch(registerUserFailure(error.response.data.errors, error.response.data.message));
        dispatch(isLoading(false));
        dispatch(addFlashMessage(error.response.data.message));
      }
      else {
        // Something happened in setting up the request that triggered an Error
        console.log(error.message);
      }
    });
  };
}
/*registerUser发送addFlashMessage的位置*/

import * as types from '../actions/actionTypes';
import deepFreeze from 'deep-freeze';
import expect from 'expect';

const INITIAL_STATE = {
    messages: []
};
const reducerFlashMessage = (state = INITIAL_STATE, action) => {
    switch (action.types) {
        case types.ADD_FLASH_MESSAGE:
            return { ...state,
                messages: [ ...state.messages, {
                    id: action.message.id,
                    style: action.message.style,
                    text: action.message.text
                }]
            };
    }
    return state;
};

export default reducerFlashMessage;
import * as types from './actionTypes';

export function addFlashMessage(message) {
      return {
        type: types.ADD_FLASH_MESSAGE,
        message

      };
    }
export function registerUser({
  timezone,
  name,
  email,
  password,
  passwordConfirmation
}) {
  return dispatch => {
    dispatch(isLoading(true));
    axios.post('/auth/signup', {
      timezone,
      name,
      email,
      password,
      passwordConfirmation
    })
    .then(response => {
      dispatch(_registerUserSuccess(response.data.errors, response.data.message));
      dispatch(isLoading(false));
      dispatch(addFlashMessage(response.data.message));
      dispatch(formReset());
      // browserHistory.push('/signin');
      setTimeout(() => {
              // dispatch(_hideNotifications());
      }, 2000);
      // document.getElementById('form').reset();
    })
    .catch(error => {
      if (error.response) {
        dispatch(registerUserFailure(error.response.data.errors, error.response.data.message));
        dispatch(isLoading(false));
        dispatch(addFlashMessage(error.response.data.message));
      }
      else {
        // Something happened in setting up the request that triggered an Error
        console.log(error.message);
      }
    });
  };
}
/*validation.js来自我创建消息对象的服务器*/

export function validateSignupForm(payload) {
    const errors = {};
    const message = {};
    if(validator.isEmpty(payload.name)) {
      errors.name = 'Name is required';
    }
    if(validator.isEmpty(payload.email)) {
      errors.email = 'Email is required';
    }
    if(validator.isEmpty(payload.password)) {
      errors.password = 'Password is required';
    }
    if(validator.isEmpty(payload.passwordConfirmation)) {
      errors.passwordConfirmation = 'Password confirmation is required';
    }
    if(validator.isEmpty(payload.timezone)) {
      errors.timezone = 'Timezone is required';
    }
    if (payload.email &&  !validator.isEmail(payload.email)) {
        errors.email = 'Please provide a correct email address.';
    }
    if (payload.password && payload.password.length < 4) {
        errors.password = 'Password must have at least 4 characters.';
    }
    if (payload.passwordConfirmation && !validator.equals(payload.password, payload.passwordConfirmation)) {
        errors.password = 'Passwords must match.';
    }
    if (!isEmpty(errors)) {
      message.id = shortid.generate(),
      message.style = 'danger';
      message.text = 'Check the form for errors.';
    }

    return {
        success: isEmpty(errors),
        message,
        errors
    };
}
export函数validateSignupForm(有效负载){
常量错误={};
const message={};
if(validator.isEmpty(payload.name)){
errors.name='name是必需的';
}
if(validator.isEmpty(payload.email)){
errors.email='需要电子邮件';
}
if(validator.isEmpty(payload.password)){
errors.password='需要密码';
}
if(validator.isEmpty(payload.passwordConfirmation)){
errors.passwordConfirmation='需要密码确认';
}
if(validator.isEmpty(payload.timezone)){
errors.timezone='需要时区';
}
if(payload.email&!validator.isEmail(payload.email)){
errors.email='请提供正确的电子邮件地址';
}
if(payload.password&&payload.password.length<4){
errors.password='密码必须至少包含4个字符';
}
if(payload.passwordConfirmation&!validator.equals(payload.password,payload.passwordConfirmation)){
errors.password='密码必须匹配';
}
如果(!isEmpty(错误)){
message.id=shortid.generate(),
message.style='danger';
message.text='检查表单是否有错误';
}
返回{
成功:isEmpty(错误),
消息
错误
};
}

你的减速机有一个打字错误。而不是

switch (action.types) {
应该读

switch (action.type) {

当提出问题时,试着把你的代码浓缩成一个简单的句子。通过此练习,您通常能够识别问题,但如果您仍然有问题,则可以更轻松地获得SSCCE的帮助。感谢您的帮助,我无法相信这一点,这只是提醒我下次要看得更好