繁体   English   中英

如何调用另一个文件中的组件? 反应原生

[英]How do I call a component in another file? React Native

我是 React Native 的新手,我很困惑如何在另一个文件中调用特定组件 function(SQLData.js 中的“runDemo”)以获得数据,然后我将推送到另一个组件文件中显示。 我试图使我的代码尽可能干净和易于理解,因此我试图将代码拆分为单独的文件而不会造成混乱。

我的代码流程是:Apps.js 从 SQLData.js 获取数据并将其作为道具发送到 FlatList.js,然后将其呈现。

下面我的文件的结果是抛出一个“不变违规。试图获取索引帧超出范围索引 NaN”

这些是下面的3个文件:

Apps.js - 主文件

import React from 'react';
import CustomList from './components/FlatList';
import SQLData from './components/SQLData';

export default function App() {
  
  return(
    //Not too sure if this is the correct way!
    var database = <SQLData />
    <CustomList data={database}/>
  );
};

FlatList.js - 用于返回带有数据的 Flatlist

import React, {useState} from 'react';
...
import ListItem from './ListItem';


/**
 * Handles the FlatList structure.
 */

export default function CustomList(props) {
    //Sets up Getter , Setter , Initial Data
    const [data, setData] = useState(props.data);
    ...

    //This is UI that will be returned
    return(

        //div block
        <View style = {styles.contentContainer}>

            <FlatList
                ListHeaderComponent = {header}
                //Sets the data for FlatList
                data = {data}
                keyExtractor = { (item) => (item.id).toString()}
                //Takes each item from the database and separates them into separate div and applies style to each one
                ItemSeparatorComponent = { () => <View style={styles.itemSeparator}></View>}
                contentContainerStyle={ {borderBottomColor:'grey', borderBottomWidth: 1} }
                //Gets item and index pair and creates a ListItem with those as props
                renderItem = { ({item, index}) => <ListItem item={item} index={index}/>}
            />
        </View>
    );
};

SQLData.js - 用于从本地 db 文件中读取数据

import React, { useState } from 'react';
import SQLite from 'react-native-sqlite-storage';
...

export default function importData(props) {
  const [helperArray, setArray] = useState([]);
  

  /** 1. First function to be called **/
  function runDemo() {
    loadAndQueryDB();
  }

  /** 2. Called when runDemo is called **/
  /*   assigns variable 'db' to opened Database */
  /*   Calls queryPeople(db) */
  function loadAndQueryDB() {
    db = SQLite.openDatabase({name : "users.db"}, openCB, errorCB);
    queryPeople(db);
  }

  /** 3. Called when loadAndQueryDB is called **/
  /*    Get the DB and applies a SQL call that if successful will call queryPeopleSuccess*/

  function queryPeople(db) {
    ...
  }

  /** 4.  [SUCCESS] Called when queryPeople SQL execution is successful **/
  /*      results - a ResultSet object */
  function queryPeopleSuccess(tx, results) {
    var len = results.rows.length;
    let localArray = [];
    //Go through each item in dataset
    for (let i = 0; i < len; i++) {
      let row = results.rows.item(i);
      localArray.push(row);
    }
    setArray(localArray);
  }

  return ({helperArray});
};

更新:已修复

应用程序.js

import React from 'react';
import CustomList from './components/FlatList';
import { Utils } from './helpers/Index.js';
/**
 * App.js calls CustomList
 */

 
//This uses functional instead of class component

export default function App() {
  const data = Utils.runDemo();
  return(
    <CustomList data={data}/>
  );
};

包含Index.jsSQLData.js的新文件夹称为“助手”

索引.js

import * as Utils from './SQLData.js';

// Export again
export {
   Utils,
};

SQLData.js

import React from 'react';
import SQLite from 'react-native-sqlite-storage';

let db;

function runDemo() {
    return loadAndQueryDB();
}

function loadAndQueryDB() {
    db = SQLite.openDatabase({ name: "users.db" }, openCB, errorCB);
    return queryPeople(db);
}

function queryPeople(db) {
    const data = db.transaction((tx) => {
        tx.executeSql('SELECT * FROM users', [], queryPeopleSuccess, 
        errorCB);
        });
    return data;
}

function queryPeopleSuccess(tx, results) {
    ...
    return localArray;
}

export {
    runDemo,
};

在我的组件文件夹“ ./components/FlatList.js

export default function CustomList(props) {
    const [data, setData] = useState(props.data);
    ...

似乎您的 SQLData 只是一个帮助器 function 而不是 React 组件,我不确定您为什么要在内部使用 state ,因为您可以直接返回结果return localArray;

现在,如果我们删除作为一个组件的东西,你可以在导入它之后像另一个 function 一样使用它

import SQLData from './components/SQLData';
<CustomList data={SQLData.runDemo()}/>

更新

由于您的 function 在另一个 function 内,因此您有 2 个选项,通过返回它使其可以在外部访问

function importData() { 
    function runDemo() {
        console.log("hi");
    }
    return {
        runDemo: runDemo
    };
}

import SQLData from './components/SQLData';
const data = SQLData();
<CustomList data={data.runDemo()}/>

或删除父 function 所以所有功能都是独立的,这样原始答案就可以了

import SQLData from './components/SQLData';
<CustomList data={SQLData.runDemo()}/>

你不会这样通过

var database = <SQLData />
<CustomList data={database}/>

你必须像这样简单地通过

<CustomList data={SQLData}/>

因为SQLData会返回一些值。

你可以使用 useContext 因为数据是交换的

暂无
暂无

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

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