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. * /}
/>
)
}
}当父组件中的数据发生更改时,子组件不会更改。用于父shouldcomponentDidUpdate不起作用。简单地说,如果在子组件中,我如何更新平面列表?
发布于 2018-10-07 20:54:27
您应该做的是在这样的子组件中使用ComponentWillRecieveProps
componentWillRecieveProps(nextProps){
if(JSON.stringify(this.props.data) !== JSON.stringify(nextProps.data)){
this.setState({ updateList: nextProps.data})
}
}然后使用
this.state.updateList 用于更新FlatList
您还可以在导航返回时从子组件显式调用主组件函数,如this和调用setState进行重命名。
https://stackoverflow.com/questions/52691666
复制相似问题