簡體   English   中英

單位列表未更新?

[英]Flatlist is not updated?

    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不起作用。 簡而言之,如果在子組件中,我該如何更新單位列表?

您應該做的是像這樣在子組件中使用ComponentWillRecieveProps

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

然后使用

this.state.updateList 

用於更新FlatList

您也可以明確的子組件航行回來時,調用主要成分的功能,像這樣和呼叫的setState重新rendring

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM