最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

为什么AsyncStorage失去了一定的价值,但另一项工作有益?

IT培训 admin 3浏览 0评论

为什么AsyncStorage失去了一定的价值,但另一项工作有益?

我用AsyncStorage存储了最后一个会话ID,但是他失去了一定的价值,我不明白为什么。

我正在制作app,我应该在运行后自动选择上一个选定的组。我这样做了,但AsyncStorage在重启应用程序后丢失了某些id,如21840。与另一个id这个工作很棒。我已尝试替换字符串,但这不起作用。我的代码:

import React, { Component } from "react";
import { Hideo } from "react-native-textinput-effects";
import FontAwesomeIcon from "react-native-vector-icons/FontAwesome";
import {
  Text,
  View,
  Picker,
  FlatList,
  AsyncStorage,
  NetInfo
} from "react-native";
import { bindActionCreators } from "redux";
import {
  getGroups,
  changeFaculty,
  groupRequest,
  searchGroup,
  getFilteredGroups,
  getFaculties,
  getSavedGroups
} from "../../store/actions";
import { connect } from "react-redux";
import GroupItem from "../other/GroupItem";
import {
  NAVBAR_COLOR,
  TEXT_COLOR_DEFAULT,
  BACKGROUND_COLOR
} from "../../../res/values/colors";
import { APP_NAME } from "../../../res/values/strings";

class HomeContainer extends Component {
  componentDidMount() {
    console.disableYellowBox = true;
    AsyncStorage.getItem("Groups")
      .then(groups => {
        if (groups && groups.length) {
          return JSON.parse(groups);
        } else {
          return [];
        }
      })
      .then(groups => this.props.getSavedGroups(groups))
      .then(() => this.makeFacultiesList(this.props.groups))
      .catch(() => {
        return [];
      });
    NetInfo.isConnected.fetch().then(isConnected => {
      if (isConnected) {
        this.props.getGroups().then(() => {
          this.makeFacultiesList(this.props.groups);
        });
      }
    });
    AsyncStorage.getItem("lastSessionGroup")
      .then(group => {
        if (group & group.length) {
          return group;
        }
      })
      .then(gr => this._onPress(gr));
  }

  getSelectedFaculty(defaultValue) {
    //this.props.changeFaculty(this.props.groups, defaultValue);
    // return defaultValue;
    AsyncStorage.getItem("selectedFaculty")
      .then(faculty => {
        if (faculty && faculty.length > 0) {
          return JSON.parse(faculty);
        } else {
          return defaultValue;
        }
      })
      .then(res => {
        return res;
      })
      .then(res => {
        if (res != this.props.faculty)
          this.props.changeFaculty(this.props.groups, res);
      });
  }

  _keyExtractor = item => item.id.toString();

  _onPress = item => {
    console.log(item);
    AsyncStorage.setItem("lastSessionGroup", item + "");
    this.props.navigator.push({
      screen: APP_NAME + ".ScheduleScreen",
      title: "Расписание " + this.getGroupNameById(item),
      animated: true,
      animationType: "slide-horizontal",
      passProps: {
        group: item
      }
    });
  };

  getGroupNameById = id => {
    return this.props.groups.filter(group => group.id == id)[0].name;
  };

  makeFacultiesList(data) {
    let faculties = [];
    data.map(faculty => {
      if (faculties.indexOf(faculty.facul) == -1) {
        faculties = [...faculties, faculty.facul];
      }
    });
    this.props.getFaculties(faculties);
    this.getSelectedFaculty(faculties[0]);
    // this.props.changeFaculty(
    //   this.props.groups,
    //   this.getSelectedFaculty(faculties[0])
    // );
    return faculties;
  }

  render() {
    return (
      <View>
        <View
          style={{
            alignItems: "center",
            flexDirection: "row",
            paddingHorizontal: 5,
            justifyContent: "space-around"
          }}
        >
          <Text
            style={{
              fontWeight: "bold",
              fontSize: 20,
              color: TEXT_COLOR_DEFAULT
            }}
          >
            Факультет
          </Text>
          <View
            style={{
              backgroundColor: "#fff",
              borderWidth: 1,
              alignItems: "center",
              paddingLeft: 10
            }}
          >
            <Picker
              selectedValue={this.props.faculty}
              style={{ width: 175, alignItems: "center", borderWidth: 1 }}
              prompt="Выберите факультет"
              onValueChange={loc => {
                this.props.changeFaculty(this.props.groups, loc);
                this.props.getFilteredGroups(
                  this.props.groups,
                  loc,
                  this.props.groupName
                );
                // this.setState({faculty: loc})
                // this.setState({facultySelected: true})
                // this.setState({group: this.state.groups.filter(group=>group.facul==this.state.faculty)[0].id})
              }}
            >
              {this.props.faculties.map((faculty, index) => (
                <Picker.Item label={faculty} value={faculty} key={index} />
              ))}
            </Picker>
          </View>
        </View>
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center",
            paddingHorizontal: 7,
            marginTop: 10
          }}
        >
          <Hideo
            //ъ\value={this.state.groupName}
            iconClass={FontAwesomeIcon}
            iconName={"search"}
            iconColor={"#fff"}
            iconBackgroundColor={NAVBAR_COLOR}
            inputStyle={{ color: TEXT_COLOR_DEFAULT }}
            labelStyle={{ color: TEXT_COLOR_DEFAULT }}
            onChangeText={text => {
              this.props.searchGroup(text);
              this.props.getFilteredGroups(
                this.props.groups,
                this.props.faculty,
                text
              );
            }}
            placeholder="Поиск группы"
            autoCapitalize="characters"
            blurOnSubmit={true}
            borderWidth={1}
          />
        </View>
        <View
          style={{
            width: "95%",
            alignSelf: "center",
            justifyContent: "flex-end",
            height: "81%",
            marginTop: 10
          }}
        >
          <FlatList
            renderItem={({ item }) => (
              <GroupItem
                title={item.name}
                id={item.id}
                onPressItem={this._onPress}
              />
            )}
            ItemSeparatorComponent={Separator}
            ListFooterComponent={Separator}
            data={this.props.filteredGroups}
            keyExtractor={this._keyExtractor}
            showsVerticalScrollIndicator={false}
            getItemLayout={(data, index) => ({
              length: 51,
              offset: 51 * index,
              index: index
            })}
            removeClippedSubviews={true}
          />
        </View>
      </View>
    );
  }
}

const Separator = () => <View style={{ height: 1 }} />;

function mapStateToProps(state) {
  return {
    groups: state.scheduleReducer.groups,
    isLoading: state.scheduleReducer.isLoading,
    faculties: state.scheduleReducer.faculties,
    faculty: state.scheduleReducer.faculty,
    filteredGroups: state.scheduleReducer.filteredGroups,
    groupName: state.scheduleReducer.groupName
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      getGroups,
      changeFaculty,
      groupRequest,
      searchGroup,
      getFilteredGroups,
      getFaculties,
      getSavedGroups
    },
    dispatch
  );
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(HomeContainer);
回答如下:

我解决这个问题。使用AsyncStorage multiGet()。像:

AsyncStorage.multiGet([
      "Groups",
      "selectedFaculty",
      "lastSessionGroup"
    ]).then(response => {
      let groups;
      if (response[0][1] && response[0][1].length) {
        groups = JSON.parse(response[0][1]);
      } else {
        groups = [];
      }
      let selectedFaculty = response[1][1];
      this.props.getSavedGroups(groups);
      let lastSession = response[2][1];
      console.log(lastSession);
      if (lastSession != null && lastSession.length) {
        this.props.navigator.push({
          screen: APP_NAME + ".ScheduleScreen",
          title: "Расписание " + this.getGroupNameById(lastSession),
          animated: true,
          animationType: "slide-horizontal",
          passProps: {
            group: lastSession
          }
        });
      }
      this.makeFacultiesList(this.props.groups);
    });

为什么AsyncStorage失去了一定的价值,但另一项工作有益?

我用AsyncStorage存储了最后一个会话ID,但是他失去了一定的价值,我不明白为什么。

我正在制作app,我应该在运行后自动选择上一个选定的组。我这样做了,但AsyncStorage在重启应用程序后丢失了某些id,如21840。与另一个id这个工作很棒。我已尝试替换字符串,但这不起作用。我的代码:

import React, { Component } from "react";
import { Hideo } from "react-native-textinput-effects";
import FontAwesomeIcon from "react-native-vector-icons/FontAwesome";
import {
  Text,
  View,
  Picker,
  FlatList,
  AsyncStorage,
  NetInfo
} from "react-native";
import { bindActionCreators } from "redux";
import {
  getGroups,
  changeFaculty,
  groupRequest,
  searchGroup,
  getFilteredGroups,
  getFaculties,
  getSavedGroups
} from "../../store/actions";
import { connect } from "react-redux";
import GroupItem from "../other/GroupItem";
import {
  NAVBAR_COLOR,
  TEXT_COLOR_DEFAULT,
  BACKGROUND_COLOR
} from "../../../res/values/colors";
import { APP_NAME } from "../../../res/values/strings";

class HomeContainer extends Component {
  componentDidMount() {
    console.disableYellowBox = true;
    AsyncStorage.getItem("Groups")
      .then(groups => {
        if (groups && groups.length) {
          return JSON.parse(groups);
        } else {
          return [];
        }
      })
      .then(groups => this.props.getSavedGroups(groups))
      .then(() => this.makeFacultiesList(this.props.groups))
      .catch(() => {
        return [];
      });
    NetInfo.isConnected.fetch().then(isConnected => {
      if (isConnected) {
        this.props.getGroups().then(() => {
          this.makeFacultiesList(this.props.groups);
        });
      }
    });
    AsyncStorage.getItem("lastSessionGroup")
      .then(group => {
        if (group & group.length) {
          return group;
        }
      })
      .then(gr => this._onPress(gr));
  }

  getSelectedFaculty(defaultValue) {
    //this.props.changeFaculty(this.props.groups, defaultValue);
    // return defaultValue;
    AsyncStorage.getItem("selectedFaculty")
      .then(faculty => {
        if (faculty && faculty.length > 0) {
          return JSON.parse(faculty);
        } else {
          return defaultValue;
        }
      })
      .then(res => {
        return res;
      })
      .then(res => {
        if (res != this.props.faculty)
          this.props.changeFaculty(this.props.groups, res);
      });
  }

  _keyExtractor = item => item.id.toString();

  _onPress = item => {
    console.log(item);
    AsyncStorage.setItem("lastSessionGroup", item + "");
    this.props.navigator.push({
      screen: APP_NAME + ".ScheduleScreen",
      title: "Расписание " + this.getGroupNameById(item),
      animated: true,
      animationType: "slide-horizontal",
      passProps: {
        group: item
      }
    });
  };

  getGroupNameById = id => {
    return this.props.groups.filter(group => group.id == id)[0].name;
  };

  makeFacultiesList(data) {
    let faculties = [];
    data.map(faculty => {
      if (faculties.indexOf(faculty.facul) == -1) {
        faculties = [...faculties, faculty.facul];
      }
    });
    this.props.getFaculties(faculties);
    this.getSelectedFaculty(faculties[0]);
    // this.props.changeFaculty(
    //   this.props.groups,
    //   this.getSelectedFaculty(faculties[0])
    // );
    return faculties;
  }

  render() {
    return (
      <View>
        <View
          style={{
            alignItems: "center",
            flexDirection: "row",
            paddingHorizontal: 5,
            justifyContent: "space-around"
          }}
        >
          <Text
            style={{
              fontWeight: "bold",
              fontSize: 20,
              color: TEXT_COLOR_DEFAULT
            }}
          >
            Факультет
          </Text>
          <View
            style={{
              backgroundColor: "#fff",
              borderWidth: 1,
              alignItems: "center",
              paddingLeft: 10
            }}
          >
            <Picker
              selectedValue={this.props.faculty}
              style={{ width: 175, alignItems: "center", borderWidth: 1 }}
              prompt="Выберите факультет"
              onValueChange={loc => {
                this.props.changeFaculty(this.props.groups, loc);
                this.props.getFilteredGroups(
                  this.props.groups,
                  loc,
                  this.props.groupName
                );
                // this.setState({faculty: loc})
                // this.setState({facultySelected: true})
                // this.setState({group: this.state.groups.filter(group=>group.facul==this.state.faculty)[0].id})
              }}
            >
              {this.props.faculties.map((faculty, index) => (
                <Picker.Item label={faculty} value={faculty} key={index} />
              ))}
            </Picker>
          </View>
        </View>
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center",
            paddingHorizontal: 7,
            marginTop: 10
          }}
        >
          <Hideo
            //ъ\value={this.state.groupName}
            iconClass={FontAwesomeIcon}
            iconName={"search"}
            iconColor={"#fff"}
            iconBackgroundColor={NAVBAR_COLOR}
            inputStyle={{ color: TEXT_COLOR_DEFAULT }}
            labelStyle={{ color: TEXT_COLOR_DEFAULT }}
            onChangeText={text => {
              this.props.searchGroup(text);
              this.props.getFilteredGroups(
                this.props.groups,
                this.props.faculty,
                text
              );
            }}
            placeholder="Поиск группы"
            autoCapitalize="characters"
            blurOnSubmit={true}
            borderWidth={1}
          />
        </View>
        <View
          style={{
            width: "95%",
            alignSelf: "center",
            justifyContent: "flex-end",
            height: "81%",
            marginTop: 10
          }}
        >
          <FlatList
            renderItem={({ item }) => (
              <GroupItem
                title={item.name}
                id={item.id}
                onPressItem={this._onPress}
              />
            )}
            ItemSeparatorComponent={Separator}
            ListFooterComponent={Separator}
            data={this.props.filteredGroups}
            keyExtractor={this._keyExtractor}
            showsVerticalScrollIndicator={false}
            getItemLayout={(data, index) => ({
              length: 51,
              offset: 51 * index,
              index: index
            })}
            removeClippedSubviews={true}
          />
        </View>
      </View>
    );
  }
}

const Separator = () => <View style={{ height: 1 }} />;

function mapStateToProps(state) {
  return {
    groups: state.scheduleReducer.groups,
    isLoading: state.scheduleReducer.isLoading,
    faculties: state.scheduleReducer.faculties,
    faculty: state.scheduleReducer.faculty,
    filteredGroups: state.scheduleReducer.filteredGroups,
    groupName: state.scheduleReducer.groupName
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      getGroups,
      changeFaculty,
      groupRequest,
      searchGroup,
      getFilteredGroups,
      getFaculties,
      getSavedGroups
    },
    dispatch
  );
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(HomeContainer);
回答如下:

我解决这个问题。使用AsyncStorage multiGet()。像:

AsyncStorage.multiGet([
      "Groups",
      "selectedFaculty",
      "lastSessionGroup"
    ]).then(response => {
      let groups;
      if (response[0][1] && response[0][1].length) {
        groups = JSON.parse(response[0][1]);
      } else {
        groups = [];
      }
      let selectedFaculty = response[1][1];
      this.props.getSavedGroups(groups);
      let lastSession = response[2][1];
      console.log(lastSession);
      if (lastSession != null && lastSession.length) {
        this.props.navigator.push({
          screen: APP_NAME + ".ScheduleScreen",
          title: "Расписание " + this.getGroupNameById(lastSession),
          animated: true,
          animationType: "slide-horizontal",
          passProps: {
            group: lastSession
          }
        });
      }
      this.makeFacultiesList(this.props.groups);
    });
发布评论

评论列表 (0)

  1. 暂无评论