Redux状态单项更新显示以前的版本

时间:2018-09-09 01:55:16

标签: javascript reactjs redux react-redux

我的数组(icdCodes)中的项目(icdCode)的更新缩减程序未在react组件内正确更新(直到重新加载整个组件)。首先,它发出重复密钥问题,因为触发操作后,数组中新更新的项与列表组件中的前一个状态项一起显示。我通过一些调整找到了解决该问题的方法,但是无论我尝试了什么,我都无法在前端正确更新此项目。

初始状态:

state = {icdCodes: []}

更新减速器:

case UPDATE_ICD_CODE:
return {
        ...state,
        icdCodes: [...state.icdCodes, action.payload]
}

这是我的react组件的摘录,其中加载了这些数组项的列表(通过映射):

  render() {
    const { icdCodes } = this.props.icdCode;

    return (
      <Card body>
        <ListGroup flush>
              <Row>
                this.icdCodes.map(({ _id, icdCode, icdCodeValue }) => (
                <div>{icdCodeValue}</div>
                )
              </Row>
        </ListGroup>
      </Card>
    );
  }
}

IcdCodeItem.propTypes = {
  getIcdCodes: PropTypes.func.isRequired,
  icdCode: PropTypes.object.isRequired
};

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

export default connect(
  mapStateToProps,
  { getIcdCodes, deleteIcdCode, updateIcdCode }
)(IcdCodeItem);

以下是action.payload返回的内容(更新后的icdCode项,其中包含“ icdCode”部分的新值):

{icdCodeVersion: "10", 
_id: "5b922fbae1c4241b54ea8aa4", 
icdCode: "I9", 
icdCodeValue: "jam jam", 
date: "2018-09-07T07:58:50.104Z", …}

以下代码仅部分解决了我的对象而不是整个对象的问题(允许我仅编辑我的对象的第一个键(不是icdCode项,而是项目中的icdCode-句法太糟了)):< / p>

return {
        ...state,
        icdCodes: state.icdCodes.map(
          icdCode =>
            icdCode._id === action.payload._id
              ? { ...icdCode, icdCode: action.payload.icdCode }
              : icdCode
        )
      };

1 个答案:

答案 0 :(得分:1)

您可以映射icdCodes数组,然后,如果元素正确(此处我正在通过_id检查),则可以对其进行更改而无需更改。

case UPDATE_ICD_CODE: {
  const icdCodes = state.icdCodes.map(icd => {
    if (icd._id === action.payload._id) {
      return { ...icd, icdCode: action.payload.icdCode };
    }
    return icd;
  });

  return { ...state, icdCodes };
}

**评论后更新**

如果您需要在此处更改多个属性,则为:

case UPDATE_ICD_CODE: {
  const { _id, icdCode, icdCodeValue } = action.payload;
  const icdCodes = state.icdCodes.map(icd => {
    if (icd._id === _id) {
      return { ...icd, icdCode, icdCodeValue };
    }
    return icd;
  });

  return { ...state, icdCodes };
}

如果要完全更改对象,则更容易:

case UPDATE_ICD_CODE: {
    const { _id } = action.payload;
    const icdCodes = state.icdCodes.map(icd =>
        icd._id === _id ? action.payload : icd
    )

    return { ...state, icdCodes };
}