【问题标题】:Redux State Change Not Re-rendering with Immutable JSRedux 状态更改不使用不可变 JS 重新渲染
【发布时间】:2017-12-17 01:18:01
【问题描述】:

当我的操作成功执行并返回我的状态并进行更改时,子组件不会重新渲染。我正在使用 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?

【问题讨论】:

    标签: reactjs redux react-redux immutable.js


    【解决方案1】:

    使用setState 方法更新状态。

    替换:

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

    与:

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

    如果您查看 State and Lifecycle - Use State Correctly 文档以了解 react;首先列出的是:

    不要直接修改状态

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

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 2020-07-26
      • 2017-03-26
      • 1970-01-01
      • 2019-02-13
      • 2020-01-20
      • 1970-01-01
      • 2021-07-08
      • 2020-07-12
      相关资源
      最近更新 更多