首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flatlist没有更新吗?

Flatlist没有更新吗?
EN

Stack Overflow用户
提问于 2018-10-07 18:36:03
回答 1查看 185关注 0票数 0
代码语言:javascript
复制
    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}/>
    )
    }
   }

子组件

代码语言:javascript
复制
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. * /}                   
            />
    )
    }
   }

当父组件中的数据发生更改时,子组件不会更改。用于父shouldcomponentDidUpdate不起作用。简单地说,如果在子组件中,我如何更新平面列表?

EN

回答 1

Stack Overflow用户

发布于 2018-10-07 20:54:27

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

代码语言:javascript
复制
componentWillRecieveProps(nextProps){
if(JSON.stringify(this.props.data) !== JSON.stringify(nextProps.data)){
   this.setState({ updateList: nextProps.data})
}
}

然后使用

代码语言:javascript
复制
this.state.updateList 

用于更新FlatList

您还可以在导航返回时从子组件显式调用主组件函数,如this和调用setState进行重命名。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52691666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档