0

When my action successfully excutes and my state is returned, with a change, the child component is not re-rendering. I am using Immutable JS to have immutable state objects.

This is the reducer:

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;
  }
}

This is the parent component:

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);

This is the child component:

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;

What do I need to change so that the child is rerendered and the constructor changes this.state.fill?

1 Answer 1

1

Use setState method to update state.

Replace:

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

With:

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

If you take a look at the State and Lifecycle - Use State Correctly documentation for react; The first thing listed is:

Do Not Modify State Directly

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

// Correct
this.setState({comment: 'Hello'});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.