Mustafa Mamun Mustafa Mamun - 3 years ago 219
Javascript Question

React component always gives last given props value

Child Component

export class MultiSelectDrawer extends React.Component {

componentDidMount(){
window.onpopstate = ()=>{
console.log(this.props.id);
}
}
render() {
const {input, id, label, showActionDrawer, toggleActionDrawer, items, closeActionDrawer} = this.props;
return (
<div>
</div>
);
}
}
MultiSelectDrawer.contextTypes = {
t: PropTypes.func.isRequired
}

export default MultiSelectDrawer;


Parent component

<td style={Object.assign({},styles.filters, styles.leftAlign)}>
<Field id="stateSearchFilter" name="stateSearchFilter" component={MultiSelectDrawer} label={this.context.t("State")} items={states} titleField='value' toggleActionDrawer = {toggleActionDrawerState} showActionDrawer = {this.state.showActionDrawerState} closeActionDrawer = {closeActionDrawerStateFilter} filterBar={filterBar}></Field>
</td>
<td style={Object.assign({},styles.filters, styles.leftAlign)}>
<Field id="prioritySearchFilter" name="prioritySearchFilter" component={MultiSelectDrawer} label={this.context.t("Priority")} items={priorities} titleField='label' toggleActionDrawer = {toggleActionDrawerPriority} showActionDrawer = {this.state.showActionDrawerPriority} closeActionDrawer = {closeActionDrawerPriorityFilter} filterBar={filterBar}></Field>
</td>


In the child componentDidMount window.onpopstate log I am expecting to see both the ids printed when browser back button is pressed. But it is only printing the second id which is prioritySearchFilter. I am quite new to React. What is wrong i am doing here?

Answer Source

The problem is that you are overwriting your first function. You are calling:

 window.onpopstate = ()=>{
      console.log(this.props.id);
    }

 window.onpopstate = ()=>{
      console.log(this.props.id);
    }

twice (in each component instance). So its like when you assign two values to the same variable (here the variable is window.onpopstate). The last assignment overwrites the first.

var x = 1;
x = 2 // now x is 2. previous value is overwritten.

Or in your case:

window.onpopstate = func1;
window.onpopstate = func2;

After these two calls window.onpopstate now points to func2

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download