amit
amit

Reputation: 10271

Component not updating on props update

I am trying to re-render a component based on update to the props from its parent. But unless I use forceUpdate() I cant get the component to re-render on its own.

This is the component where I am updating the component and passing it to the child component:

var StoryContainer = React.createClass({

    propTypes: {
        currentItem: React.PropTypes.number.isRequired
    },

    componentWillMount: function(){
        metrics.currentItem = 0;
        metrics.nextItem = 2;
    },

    handleClick: function(ctx){
        metrics.currentItem++;
        metrics.nextItem++;

        var data = this.props.data.slice(metrics.currentItem, metrics.nextItem);
        data[0].idx = metrics.currentItem
        data[1].idx = metrics.nextItem - 1;
        console.log(ctx);
        ctx.props.data = data;
        ctx.props.idx = metrics.currentItem;
        // this.forceUpdate();
    },

    render: function(){
        return (
            <StoryItems data={this.props.data.slice(metrics.currentItem,metrics.nextItem)} onChange={this.handleClick} />
        )   
    }
});

This is the class to which I am passing the updated props.

var StoryItems = React.createClass({
    componentWillReceiveProps: function(nextProps){
        console.log(nextProps);
    },
    componentWillMount: function(a){
        console.log('StoryItems:componentWillMount', a);
    },
    componentDidMount: function(a){
        console.log('StoryItems:componentDidMount', a);
    },
    shouldComponentUpdate: function(nextProps){
        console.log('StoryItems:shouldComponentUpdate', nextProps);
        return true;
    },
    render: function(){
        return (
            <View style={styles.wrapper}>
                <Story data={this.props.data[1]} onChange={this.handleItemUnmount} />
                <Story data={this.props.data[0]} onChange={this.handleItemUnmount} />
            </View>
        );
    },
    handleItemUnmount: function(ctx){
        // console.log('here', ctx);
        this.props.onChange(this);
    },

});

module.exports = StoryItems;

Can anyone spot something wrong? React n00b here.

Upvotes: 1

Views: 3295

Answers (1)

Anders Ekdahl
Anders Ekdahl

Reputation: 22943

When StoryContainer.handleClick is called, nothing is done to tell React that you need to re-render StoryContainer, which is what sends new props to StoryItems. You are mutating the metrics variable which React doesn't know about, so React won't know to re-render anything.

You should keep the metrics variable as state on the StoryContainer component, and then update that with setState. The call to setState on StoryContainer will tell React to re-render it (since its state has changed) and that will pass new props to StoryItems.

Upvotes: 5

Related Questions