2015-05-04 113 views
1

我想重新渲染組件的基礎上,從它的父母的道具更新。但是除非我使用forceUpdate(),否則我不能讓組件重新渲染。組件不更新道具更新

這是我更新的組件,並將其傳遞給子組件的組件:

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

這是我想過去更新道具類。

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; 

任何人都可以發現錯誤?在這裏反應n00b。

回答

5

StoryContainer.handleClick被調用時,沒有任何事情可以告訴React你需要重新渲染StoryContainer,這是發送新道具到StoryItems。你正在改變React不知道的metrics變量,所以React不會知道重新渲染任何東西。

您應該在組件上保留metrics變量state,然後用setState更新該組件。在StoryContainersetState的電話會告訴React重新渲染它(因爲它的狀態已經改變)並且會通過新的道具到StoryItems

+0

太棒了。非常感謝。 – amit