2017-12-17 8 views
0

Wenn meine Aktion erfolgreich ausgeführt wird und mein Status mit einer Änderung zurückgegeben wird, wird die untergeordnete Komponente nicht erneut gerendert. Ich verwende Immutable JS, um unveränderliche Statusobjekte zu haben.Redux-Statusänderung wird nicht mit unveränderlichem JS erneut gerendert

Dies ist das Reduktions:

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

Dies ist die übergeordnete Komponente:

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

Dies ist die untergeordnete Komponente:

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; 

Was muss ich ändern, so dass Das Kind wird neu gerendert und der Konstruktor ändert this.state.fill?

Antwort

1

Verwenden Sie die setState Methode, um den Status zu aktualisieren.

ersetzen:

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

mit:

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

Wenn Sie einen Blick auf die State and Lifecycle - Use State Correctly Dokumentation reagieren; Das erste, was aufgeführt ist:

modifizierte Staat nicht direkt

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

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