Redux状态更改不使用不可变JS重新呈现

时间:2017-12-17 01:18:02

标签: reactjs redux react-redux immutable.js

当我的操作成功执行并返回状态并进行更改时,子组件不会重新呈现。我使用Immutable JS来拥有不可变的状态对象。

这是减速器:

const initialState = {
  sectionsArray: [],
};

export default function seatingChartSections(state = fromJS(initialState), action) {
  switch (action.type) {
    case actionTypes.LOAD_SEATING_CHART_SECTIONS:
      return fromJS({ sectionsArray: action.seatingChartSections });

    case actionTypes.CLICK_SECTION:
      return state.updateIn(['sectionsArray'], (list) => {
        const index = list.findIndex(item => item.get('_key') === action.section);
        if (list.getIn([index, 'selected']) === true) {
          return list.setIn([index, 'selected'], false);
        }
        return list.setIn([index, 'selected'], true);
      });

    default:
      return state;
  }
}

这是父组件:

class SeatingChartSections extends Component {
  render() {
    return (
      this.props.seatingChartSections.sectionsArray.map(section => (<SeatingChartSection
        key={section._key}
        section={section}
        onClick={this.selectSection}
      />))
    );
  }
}

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

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

这是子组件:

class SeatingChartSection extends Component {
  constructor(props) {
    super(props);
    if (this.props.section.selected) {
      this.state = {
        fill: '#1aa3ff',
        stroke: '#4d4dff',
      };
    }
    if (!this.props.section.selected) {
      this.state = {
        fill: '#cce6ff',
        stroke: '#4d4dff',
      };
    }
  }
  render() {
    return (
      <polygon
        onClick={this.props.onClick}
        id={this.props.section._key}
        fillOpacity={0.4}
        fill={this.state.fill}
        stroke={this.state.stroke}
        points={this.props.section.points}
      />
    );
  }
}

export default SeatingChartSection;

我需要更改什么才能重新渲染子项,构造函数会更改this.state.fill?

1 个答案:

答案 0 :(得分:1)

使用setState方法更新状态。

替换:

this.state = {
    fill: '#cce6ff',
    stroke: '#4d4dff',
};

使用:

this.setState({
    fill: '#cce6ff',
    stroke: '#4d4dff',
});

如果你看一下State and Lifecycle - Use State Correctly文件的反应;列出的第一件事是:

  

不要直接修改状态

// Wrong
this.state.comment = 'Hello';

// Correct
this.setState({comment: 'Hello'});