Как обновить данные в первом компоненте при добавлении данных в другой компонент - PullRequest
0 голосов
/ 23 октября 2018

У меня есть два компонента с базой данных области, один для листинга, а другой для добавления данных.Но моя проблема в том, что я не могу обновить список, когда данные добавляются во второй компонент.Я также пытался прослушивать состояние приложения, но он не запускается, когда пользователь появляется на первом экране.

Это компонент списка

import React, { Component } from "react";
import AppScreen from "../AppScreen.js";
import realm from "../databases/RealmController.js";
import colors from "../Ui/colors.js";
import Swipeout from "react-native-swipeout";
import { Icon } from "react-native-vector-icons";
import { NavigationActions } from "react-navigation";
import Dash from "react-native-dash";
import AppStateListener from "react-native-appstate-listener";
import {
  AppState,
  AppRegistry,
  StyleSheet,
  Text,
  Image,
  Button,
  View,
  FlatList,
  TouchableHighlight,
  TouchableOpacity,
  Alert,
  StatusBar,
  TextInput
} from "react-native";
type Props = {};
export default class ReminderList extends Component<Props> {
  state = {
    data: [],
    loading: true,
    refresh: false,
    appState: AppState.currentState
  };
  static navigationOptions = {
    header: null,
    title: " List"
  };


 handleActive() {
 console.warn("The application is now active!");
}

 handleBackground() {
 console.warn("The application is now in the background!");
}

 handleInactive() {
 console.warn("The application is now inactive!");
}

  componentDidMount() {
    //this.fetchData();
    AppState.addEventListener("change", this.handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener("change", this.handleAppStateChange);
  }
  gotoAddReminder = () => {
    //  handle navigation
    this.props.screenProps.rootNavigation.navigate("addReminder");
  };


  handleAppStateChange = nextAppState => {
    if (nextAppState === "active") {
      this.setState({ data: null });
      this.fetchData();
      this.setState({ refresh: true });
    //  console.warn("hello i active");
      //this.flatList.scrollToIndex({ animated: true, index: 0 });

    }
   else {
     this.setState({ refresh: false });
  //   console.warn("hello i inactive");


   }

    this.setState({ appState: nextAppState });
  };
  fetchData() {
    let reminderList = realm.objects("Reminder");
    this.setState({ data: reminderList });
  }

  renderClientRow(item) {
    return (
      <TouchableHighlight underlayColor="rgba(192,192,192,1,0.6)">
        <View style={styles.cardView}>
          <View style={styles.dateView}>
            <Text style={styles.dateText}>18</Text>
            <Text style={styles.monthText}>Jan</Text>
          </View>
          <View
            style={{
              width: 1,
              backgroundColor: colors.darkGray,
              marginLeft: 15,
              marginRight: 20
            }}
          />

          <View style={{ flexDirection: "row", marginTop: 15, width: "100%" }}>
            <View style={{ flexDirection: "column" }}>
              <Text style={styles.titleText}>{item.name}</Text>
              <Text style={(styles.item, { marginTop: 5 })}>location</Text>

              <Dash
                style={{
                  width: 300,
                  marginTop: 10,
                  height: 1,
                  marginRight: 15
                }}
              />
              <View
                style={{
                  flex: 1,
                  flexDirection: "row",
                  marginTop: 5,
                  marginBottom: 15
                }}
              >
                <Image
                  style={{
                    width: 15,
                    height: 15,
                    marginTop: 5,
                    marginRight: 10
                  }}
                  source={require("../Image/ic_date.png")}
                />
                <Text style={styles.item}>0.40 pm</Text>
              </View>
            </View>
          </View>
        </View>
      </TouchableHighlight>
    );
  }

  render() {
    return (
      <View style={styles.container}>
      <AppStateListener
       onActive={this.handleActive}
       onBackground={this.handleBackground}
       onInactive={this.handleInactive}
     />
        <FlatList
        ref={(c) => { this.flatList = c }}
          data={this.state.data}
          extraData={this.state.refresh}
          renderItem={({ item }) => this.renderClientRow(item)}
          keyExtractor={item => item.id}
        />

        <TouchableOpacity
          activeOpacity={0.5}
          onPress={() => {
            this.gotoAddReminder();
          }}
          style={styles.TouchableOpacityStyle}
        >
          <Image
            source={{
              uri:
                "https://reactnativecode.com/wp-content/uploads/2017/11/Floating_Button.png"
            }}
            style={styles.FloatingButtonStyle}
          />
        </TouchableOpacity>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 0
  },
  MainContainer: {
    justifyContent: "center",
    flex: 1,
    margin: 10
  },
  TouchableOpacityStyle: {
    position: "absolute",
    width: 50,
    height: 50,
    alignItems: "center",
    justifyContent: "center",
    right: 30,
    bottom: 30
  },
  FloatingButtonStyle: {
    resizeMode: "contain",
    width: 50,
    height: 50
  },
  cardView: {
    backgroundColor: "#fff",
    borderWidth: 0.5,
    paddingLeft: 15,
    paddingRight: 10,
    marginLeft: 10,
    marginTop: 10,
    marginRight: 10,
    borderRadius: 5,
    flexDirection: "row"
  },
  item: {
    fontSize: 16,
    color: colors.darkGray
  },
  itemRight: {
    fontSize: 18,
    textAlign: "right"
  },
  titleText: {
    fontSize: 20,
    color: "black",

    fontWeight: "400"
  },
  dateText: {
    fontSize: 32,
    color: colors.appColor,

    fontWeight: "500"
  },
  monthText: {
    fontSize: 22,
    color: colors.appColor,

    fontWeight: "500"
  },
  dateView: {
    alignItems: "center",
    justifyContent: "center",
    flexDirection: "column",
    marginLeft: 15,
    marginRight: 15,
    marginTop: 15,
    marginBottom: 15
  },
  rightText: {
    fontSize: 22,
    color: "black",
    textAlign: "right",
    fontWeight: "bold"
  },
  myStarStyle: {
    color: "yellow",
    backgroundColor: "transparent",
    textShadowColor: "black",
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2
  },
  myEmptyStarStyle: {
    color: "white"
  }
});

Это компонент AddData

import React, { Component } from "react";
import realm from "../databases/RealmController.js";
import styles from "../Ui/AddClientStyles.js";
import { TextInputLayout } from "rn-textinputlayout";
import DatePicker from "react-native-datepicker";
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableHighlight,
  Button,
  View,
  ScrollView,
  Image,
  Alert,
  StatusBar,
  TextInput
} from "react-native";
const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

type Props = {};
export default class AddReminder extends Component<Props> {
  state = {
    to: "",
    from: "",
    name: "",
    note: "",
    location: ""
  };
  handlePress = async () => {
    var Id = realm.objects("Reminder").length + 1;
    realm.write(() => {
      realm.create("Reminder", {
        id: Id,
        name: this.state.name,
        note: this.state.note,
        location: this.state.location,
        to: this.state.to,
        from: this.state.from

      });
    });

    this.props.navigation.goBack();

  };



  render() {
    return (
      <ScrollView style={styles.container}>
        <View style={styles.container}>
          <View style={styles.profileContainer} />
          <View style={styles.bottomContainer}>
            <Text style={[styles.titleText, styles.titleStyle]}>
              Basic Information
            </Text>
            <TextInputLayout style={{ marginTop: 0 }}>
              <TextInput
                style={styles.textInput}
                placeholder={"Reminder Title"}
                onChangeText={text => this.setState({ name: text })}
              />
            </TextInputLayout>
            <TextInputLayout style={styles.inputLayout}>
              <TextInput
                style={styles.textInput}
                placeholder={"Note"}
                onChangeText={text => this.setState({ note: text })}
              />
            </TextInputLayout>
            <TextInputLayout style={styles.inputLayout}>
              <TextInput
                style={styles.textInput}
                placeholder={"Location"}
                onChangeText={text => this.setState({ location: text })}
              />
            </TextInputLayout>

            <Text style={[styles.titleText, styles.titleStyle]}>
              Date & Time
            </Text>
            <View style={styles.dateToContainer}>
              <View style={{ flexDirection: "column", width: "30%" }}>
                <Text style={styles.textInput}>From</Text>
              </View>

              <View styles={{ flexDirection: "column", width: "70%" }}>
                <DatePicker
                  style={{ width: 200 }}
                  date={this.state.from}
                  mode="datetime"
                  format="YYYY-MM-DD HH:mm"
                  confirmBtnText="Confirm"
                  cancelBtnText="Cancel"
                  customStyles={{
                    dateIcon: {
                      position: "absolute",
                      left: 0,
                      top: 4,
                      marginLeft: 0
                    },
                    dateInput: {
                      marginLeft: 36
                    }
                  }}
                  minuteInterval={10}
                  onDateChange={datetime => {
                    this.setState({ from: datetime });
                  }}
                />
              </View>
            </View>

            <View style={styles.dateContainer}>
              <View style={{ flexDirection: "column", width: "30%" }}>
                <Text style={styles.textInput}>To</Text>
              </View>

              <View styles={{ flexDirection: "column", width: "70%" }}>
                <DatePicker
                  style={{ width: 200 }}
                  date={this.state.to}
                  mode="datetime"
                  format="YYYY-MM-DD HH:mm"
                  confirmBtnText="Confirm"
                  cancelBtnText="Cancel"
                  customStyles={{
                    dateIcon: {
                      position: "absolute",
                      left: 0,
                      top: 4,
                      marginLeft: 0
                    },
                    dateInput: {
                      marginLeft: 36
                    }
                  }}
                  minuteInterval={10}
                  onDateChange={datetime => {
                    this.setState({ to: datetime });
                  }}
                />
              </View>
            </View>


            <TouchableHighlight
              style={styles.btnStyle}
              onPress={() => {
                this.handlePress();
              }}
              underlayColor="#fff"
            >
              <Text style={styles.btnText}>Add Reminder</Text>
            </TouchableHighlight>

            <TouchableHighlight
              style={{marginTop:20}}>
              <Text/>

            </TouchableHighlight>
          </View>
        </View>
      </ScrollView>
    );
  }
}

1 Ответ

0 голосов
/ 23 октября 2018

Когда вы используете this.props.navigation.goBack();, эти компоненты не визуализируются снова или не вызывают какой-либо метод, который компонент может использовать this.props.navigation.navigate('your_route_path');

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...