单位列表未更新?

时间:2018-10-07 18:36:03

标签: reactjs react-native

    class Parent extends React.Component {
      constructor(props){
      super(props);
      this.state={data:[]}
      }
      componentDidMount(){         
     / * I am loading data from the server * /
        } 
      ratingCompleted=(id,favourite,i)=>{
        if(favourite===0){
           CustomerApi.AddFavourite(id);
         }
         else{
           let newState = Object.assign({}, this.state.JSON_from_server);
           newState[i].favourite = 0; 
           this.setState({JSON_from_server:newState,refresh:!this.state.refresh});}}
    render(){
     return(
        <Child data={this.state.data} refresh={this.state.refresh} 
         ratingCompleted={this.ratingCompleted}/>
    )
    }
   }

子组件

class Child extends React.Component {
      constructor(props){
      super(props);
      this.state={refresh:this.props.refresh}
      }
       renderItem(data) {     
let {item, index}  = data;      
let i=this.props.JSON_from_server.indexOf(item); 
    render(){
  return(
    <View>
    <AirbnbRating  count={1} defaultRating={item.favourite} size={30} showRating={false} onFinishRating={()=>{this.props.ratingCompleted(item.id,item.favourite,i);}}/>
    </View>
 )
}
}
     <FlatList  
                   keyExtractor = {( item, index ) => index.id }
                   data = { this.props.data}
                   renderItem={this.renderItem.bind(this)}
                   extraData={this.props.refresh}{
                  / * set even extraData = {this.props}, extraData = 
                    {this.state.refresh} or even subscribed to the parent 
                     component so the update did not work. * /}                   
            />
    )
    }
   }

并且当父级组件中的数据更改时,子级也不会更改。用于父应该componentDidUpdate不起作用。 简而言之,如果在子组件中,我该如何更新单位列表?

1 个答案:

答案 0 :(得分:0)

您应该做的是像这样在子组件中使用ComponentWillRecieveProps

componentWillRecieveProps(nextProps){
if(JSON.stringify(this.props.data) !== JSON.stringify(nextProps.data)){
   this.setState({ updateList: nextProps.data})
}
}

然后使用

this.state.updateList 

用于更新FlatList

向后导航时,您也可以从子组件显式调用Main Component函数,例如this并调用setState进行重新渲染