【问题标题】:React Native Sqlite Storage: db.transaction() function is not executedReact Native Sqlite 存储:未执行 db.transaction() 函数
【发布时间】:2019-05-16 16:46:52
【问题描述】:

我正在使用 React-native-sqlite-storage (React native CLI)。问题是当我查询 sqlite 时 getmysqliData 不会执行 tx.executeSql 函数。我不知道为什么。

整个代码是这样的: https://gist.github.com/BravenxX/247f97c0576881616c24d197cdd137f6

关于代码:

state: data: [--DATA--] .... 是临时的,这应该用 getMysqliData 函数中的 sqlite 元素替换。

这是 2 个数组,因为我将它们用作实时过滤器(顺便说一句,它与 sqlite 无关)

const db = SQLite.openDatabase({ name: "geslub", createFromLocation: "~databases/geslub.db" });

class TablaActProgramadas extends Component{
  constructor(props){
    super(props);
    this.state={
      value: '',
      isLoading: true,
      data:[
        {'Faena': 'aDDLB', 'Planta': 'taller Titan', 'Linea': 'Kmotasú', 'Equipo': 'Caex', 'Componente': 'N/A'}
      ],
      arrayholder: [
        {'Faena': 'aDDLB', 'Planta': 'taller Titan', 'Linea': 'Kmotasú', 'Equipo': 'Caex', 'Componente': 'N/A'}
      ],
    };

  };

  async componentDidMount(){
    await  this.getMysqliData();
    console.log('TERMINO: ComponenntDIDMOUNT')
  }

  getMysqliData(){
    const sql = 'SELECT * FROM actividades_programadas';

    db.transaction((tx) => {

      //TX.EXECUTESQL is not executed!!

      tx.executeSql(sql, [], (tx, results) => {
          if(results.rows._array.length > 0){

            this.setState({
              data: results.rows_array,
              arrayholder: results.rows_array,
              isLoading: false
            })

          }else{
            Alert.alert('ERROR en la carga de datos')

          }
        });
    });

  }

  componentWillUnmount() {
    this.closeDatabase();
  }

  closeDatabase = () => {
    if (db) {
        db.close();
    } else {
        console.log("Database no estaba abierta");
    }
  }

renderHeader = () => {
  return (
      <SearchBar
        placeholder="Filtro general..."
        lightTheme
        round
        onChangeText={text => this.searchFilterFunction(text)}
        autoCorrect={false}
        value={this.state.value}
      />
  );
};

searchFilterFunction = text => {
    this.setState({
      value: text,
    });

    const newData = this.state.arrayholder.filter(item => {
      const itemData = `${item.Faena.toUpperCase()} ${item.Planta.toUpperCase()} ${item.Linea.toUpperCase()}`;
      const textData = text.toUpperCase();

      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      data: newData,
    });
  };

  render(){
    if(this.state.isLoading)
      return (
          <View style={stylesLoading.container}>
                <View>
                  <ActivityIndicator size="large" color="lightblue"/>
                </View>

                <View>
                    <Text style={stylesLoading.texto}>
                        Descargando datos... 
                    </Text>
                </View>
            </View>
      )
    else
      return(
       <FlatList
          data={this.state.data}
          showsVerticalScrollIndicator={false}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({item}) =>(
            <TouchableOpacity onPress={() => this.props.navigation.navigate('RealizarActProgramadas', {
              faena: `${item.Faena}`,       //ENVIAR ID DE LA ACTIVIDAD A REALIZAR
              otherParam: 'anything you want here',
            })}>

              <ListItem
                title={`Faena: ${item.Faena}`}
                subtitle={`Planta: ${item.Planta}\nLinea: ${item.Linea}`}
              />
            </TouchableOpacity>
          )}
          ItemSeparatorComponent={this.renderSeparator}
          ListHeaderComponent={this.renderHeader()}
        />
      );
  }
}

【问题讨论】:

    标签: android sql reactjs sqlite react-native


    【解决方案1】:

    我也有同样的问题。发生这种情况是因为您打开 DasaBase 是创建一个新的数据库文件而不使用您导入的文件。 在我的 android 案例中,我需要将 de sqlite 文件放入 android/src/main/assets/www/test.db

    并使用此配置打开:

    var db = openDatabase({name: 'test.db', createFromLocation: 1}, () => {
      console.log("Database OPENED");
    }, (err) => {
      console.log("SQL Error: " + err);
    });
    

    这在文档https://github.com/andpor/react-native-sqlite-storage#importing-a-pre-populated-database中有更好的描述

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-28
      • 2020-06-11
      • 1970-01-01
      • 2022-10-14
      • 2015-06-23
      • 2016-09-10
      • 2022-06-15
      • 2021-04-25
      相关资源
      最近更新 更多