简体   繁体   中英

How to setState in different component React native?

My data from the api is loaded in a component and returns a view containing the values, which does show in the other component. But I want an activity indicator on that page to show until the data is completely loaded.

I've followed some tutorials about setState with parent-child, child-parent, sibling-sibling and parentless relations. But none seem to work the way I want it.

This is the screen that shows first. It starts with the 'refreshing' view, which will show an activityindicator until the state.refreshing is set to false.

export default class AgendaScreen extends React.Component {
    static navigationOptions = {
        title: "Agenda" 
    };
    constructor(props) {
        super(props);
        this.state={
            refreshing: true
        }

    }

    render() {
        if (this.state.refreshing){
            return(
                //loading view while data is loading
                <ImageBackground source={ScreenBackground} style={styles.container}>
                    <View style={{flex:1, paddingTop:20}}>
                        <ActivityIndicator />
                    </View>
                </ImageBackground>
            )
        }  
        return(
            <ImageBackground source={ScreenBackground} style={styles.container}>
                <ScrollView>
                <ImageBackground style={[styles.header,{justifyContent:'flex-end'}]} source = {HeaderImage}>
                    <Text style={{color:'white', fontSize:12, alignSelf:'center', backgroundColor:'transparent', marginBottom:2}}>
                        Complete summary
                    </Text>
                </ImageBackground>
                    <Text style={styles.text}>Agenda</Text>
                    <Dates />
                </ScrollView>
            </ImageBackground>
        );

    }
}

This is the dates component, which gives me the view that I call with in the previous code block.

export default class Dates extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        data:[],
        fill:[],
        refreshing:true,
        dates:[],
        list:[]
    }
}

componentDidMount() {
    this.getData();
}

getData() {
    fetch("API")
    .then((result)=>result.json())
    .then((res=>{
        this.setState({
            data:res,
            refreshing:false
        });
        this.setState({
            fill:this.state.data[0]
        });
        this.getDates();
        this.loop();

    }))
    .catch(error =>{
        console.error(error);
    });
};

onRefresh() {
    //Clear old data
    this.setState({
        data:[]
    });
    //Function to call api for latest data
    this.getData();
};

getDates() {
    var str = t(this.state.test, 'content.rendered').safeString
    var arr = str.split(',');
    var dates = [];
    arr.forEach(function(e) {
          dates.push(e.match(/;(\d{0,2}.[a-zA-Z]+)/g)[0].replace(';',''));
        });
    this.setState({
        dates: dates
    }) 
};
tempList=[];
loop(){
    for (x=0;x<this.state.data.length;x++)
    {
        var fill=this.state.data[x]
        this.tempList.push(
            <View style={{flex:1}}>
            <FlatList
                data={[fill]}
                renderItem={({item})=>
                    <View>
                        <Text style={styles.text}>
                        {t(item, 'title.rendered').safeObject}
                        </Text>
                    </View>
            }
            refreshControl={
                <RefreshControl 
                    //refresh control used for pull to refresh
                    refreshing={this.state.refreshing}
                    onRefresh={this.onRefresh.bind(this)}
                />
            }
            keyExtractor={(item, index) => index.toString()}
        /></View>
        )
    }
    this.setState({
        list:this.tempList
    })
}

    render() {    
        return(
          <View style={{flex:1, borderWidth:10}}><Text></Text>{this.state.list}
          </View>
        );
    }
}

What I need is when Dates succesfully loaded his data from the api and returns the view, that the AgendaScreen state.refreshing will be stated to false.

Add below to your AgendaScreen Component

this.refresHandler = (e) =>{

    this.setState({   
     refreshing:e
})
}

Add below props inside <Dates />

<Dates refresHandler={this.refresHandler}/>

change below code in Dates Component

getData() {
    fetch("API")
    .then((result)=>result.json())
    .then((res=>{
        this.setState({
            data:res,
            refreshing:false
        });
        this.setState({
            fill:this.state.data[0]
        });
        this.getDates();
        this.loop();

    }))
  .then(() =>{
      this.props.refresHandler(this.state.refreshing)
   })
    .catch(error =>{
        console.error(error);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM