在Redux中替换状态不变的数组中的对象

时间:2018-09-11 19:51:59

标签: reactjs react-redux

我正在尝试编辑对象,并使用React和Redux将其替换为数组:

case EDIT_LANGUAGE:
  let languages = [...state.languageSkills];
  languages[languages.findIndex(el => el.id === action.payload.id)] = action.payload;
  return {
    ...state,
    languageSkills: languages
  };

'languages'数组在return语句之前看起来为find,但状态未重新呈现。我想我正在某种程度上改变状态。其他动作(删除,获取,设置)运行良好。有提示吗?

编辑。这是应呈现的组件的相关部分

import { setLanguages, getLanguages } from '../../actions';
import {connect} from 'react-redux';
import {bindActionCreators} from "redux"
import React, { Component } from 'react';

class UserProfile extends Component {
  constructor(props) {
    super(props);
  }

  render() {   
    const languageSkillItems = this.props.languageSkills.map((languageSkill) => {
      return (
        <LanguageSkillItem key={languageSkill.id} item={languageSkill} />
      )
    });

    return (
        <div className="profile">            
            <Language languageSkillItems={languageSkillItems} />            
        </div>
    )
    } 
}

const mapStateToProps = (state) => {
  return {
    languageSkills: state.languageSkills
  };
};


const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators({ setLanguages, getLanguages }, dispatch)
  }
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(UserProfile

);

1 个答案:

答案 0 :(得分:3)

您需要创建一个新的数组引用,最简单的方法就是使用map,如下所示:

case EDIT_LANGUAGE:
  const languageSkills = state.languageSkills.map(el => {
    if(el.id === action.payload.id) {
        return action.payload;
    }
    return el;
  });
  return {
    ...state,
    languageSkills
  };