That is what I am talking about. You will probably want to reorganize this a few times, but in general here, as I think, it will look at the end. I have yet to learn how to use life cycle functions correctly, and I'm not sure if you will need them right now when I think about it.
appContainer.js
I substantially deleted your NavigatorIOS. I think it was a mistake. Instead, I replace them with components, passing the data in the form of props, including a callback function for pressing a button. I moved the addData function to a level.
class AppContainer extends Component { constructor(props) { super(props); this.state = { selectedTab: 'data-list', dataLen: 0 } AsyncStorage.getItem("all-data") .then((data)=>{ if(!data) { data = "[]"; } var dataObj = JSON.parse(data); this.setState({ dataLen : dataObj.length }); }); this.addData.bind(this); } addData() { AsyncStorage.getItem("all-data") .then((data)=>{ if(!data) { data = "[]"; } var dataObj = JSON.parse(data); dataObj.push({ val: Date.now() }); AsyncStorage.setItem("all-data", JSON.stringify(dataObj)); this.setState({ dataLen: dataObj.length }); }); } render() { return ( <TabBarIOS style={styles.container}> <TabBarIOS.Item title="Add Data" selected={this.state.selectedTab == 'add-data'} onPress={()=> this.setState({selectedTab: 'add-data'})} > <AddData onButtonPress={this.addData} dataLen={this.state.dataLen} /> </TabBarIOS.Item> <TabBarIOS.Item title="Data List" selected={this.state.selectedTab == 'data-list'} onPress={()=> this.setState({selectedTab: 'data-list'})} badge={this.state.dataLen} > <DataList dataLen={this.state.dataLen} /> </TabBarIOS.Item> </TabBarIOS> ); } }
addData.js
This will greatly simplify your subcomponents ...
class AddData extends Component { constructor(props) { super(props); } render() { return ( <View style={styles.container}> <Text>{this.props.dataLen}</Text> <TouchableHighlight onPress={this.props.onButtonPress} style={styles.button}> <Text style={styles.buttonText}>Plus One</Text> </TouchableHighlight> </View> ); } }
dataList.js
class PlayerList extends Component { constructor(props) { super(props); } render() { return ( <View style={styles.container}> <Text>{this.props.dataLen}</Text> </View> ); } }
Chris geirman
source share