Table 状态更新后不重新渲染组件

Table Component is not re-rendered after state update

我有一个 table 组件用于显示一些数据。调度一个动作后,状态中的 table 数据正在改变。但是我的 table 组件没有更新。它仅在我单击 table 的另一行中的另一个单选按钮时更新。我希望我的组件在数据更改时重新呈现。这是我的代码:

const mapStateToProps = state => ({
  evaluationData: evaluationResultsSelector(state)
});

const mapDispatchToProps = dispatch => ({
  setSelectedEvaluationRecord: record =>
    dispatch(setSelectedEvaluationRecord(record))
});


export default connect(mapStateToProps,
  mapDispatchToProps
  EvaluationDataTable,  
);

我的组件是这样的:

import React from 'react';
import Table from 'antd/lib/table';
import 'antd/lib/table/style/css';
import "antd/dist/antd.css";
import { columnEvaluation } from './evaluationDataStructure';

class EvaluationDataTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [0], // Check here to configure the default column
    };
  }
  // shouldComponentUpdate(prevProps, prevState) {
  //   return (prevProps.results !== this.props.results || prevState.selectedRowKeys !== this.state.selectedRowKeys);
  // }
  onRowChange = selectedRowKeys => {
    if (selectedRowKeys.length > 1) {
      const lastSelectedRowIndex = [...selectedRowKeys].pop();
      this.setState({ selectedRowKeys: lastSelectedRowIndex });
    }
    this.setState({ selectedRowKeys });
  };

  onRowSelect = (record) => {
    this.props.setSelectedEvaluationRecord(record)
  };

  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      type: 'radio',
      selectedRowKeys,
      onChange: this.onRowChange,
      onSelect: this.onRowSelect
    };
    return (
      <React.Fragment>
        <div style={{ marginBottom: 16 }} />
        <Table
          rowSelection={rowSelection}
          columns={columnEvaluation}
          dataSource={this.props.evaluationData}
        />
      </React.Fragment>
    );
  }
}

export default EvaluationDataTable;

当我在另一行中单击时,table 会在我的 setState 被触发时重新呈现,但是当数据发生变化时,table 不会重新呈现。只有当我点击另一行时。如何处理?非常感谢

我的 reducer 也改变了 table 是这样的:

case ACTION_TYPES.EDIT_EVALUATION_RESULTS: {
      const evaluationResults = state.evaluationResults;
      const editedRecord = action.payload.editedEvaluationData;
      evaluationResults.forEach((item, i)  => {
        if (item.id === editedRecord.id) {
          evaluationResults[i] = editedRecord;
        }
      });
      return {
        ...state,
        evaluationResults
      };
    }

OP 已经推断出了问题。

 const evaluationResults = state.evaluationResults;

这导致 state-mutation 违反了 Redux 原则。尽管在 OP 的后续代码中更新了状态值,但更改是对引用中的相同初始对象进行的。 Redux 没有将它注册为 new-state 所以它发现不需要 re-render 我们的组件。要让您的 connected-component 变为 re-render,我们需要一个全新的 redux-state。

为此,我们需要像这样创建一个 brand-new 的 evaluationResults 副本,然后 OP 的功能将按预期工作:

const evaluationResults = [...state.evaluationResults];