简体   繁体   English

如何在不同的组件React Native中设置setState?

[英]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. 我从api获得的数据已加载到一个组件中,并返回一个包含值的视图,该视图确实显示在另一个组件中。 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. 我已经关注了一些有关setState的教程,其中包含setparent-child,child-parent,兄弟姐妹-sibling和无父母关系。 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. 它以“刷新”视图开始,该视图将显示一个活动指示器,直到state.refreshing设置为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. 我需要的是,当Dates从api成功加载他的数据并返回视图时,AgendaScreen state.refreshing将声明为false。

Add below to your AgendaScreen Component 将以下内容添加到您的AgendaScreen组件中

this.refresHandler = (e) =>{

    this.setState({   
     refreshing:e
})
}

Add below props inside <Dates /> <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);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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