【问题标题】:How do I call a component in another file? React Native如何调用另一个文件中的组件?反应原生
【发布时间】:2020-06-29 17:37:10
【问题描述】:

我是 React Native 的新手,我对如何在另一个文件中调用特定组件函数(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});
};

更新:已修复

Apps.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

的新文件夹调用“帮助程序”

Index.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);
    ...

【问题讨论】:

    标签: android ios reactjs react-native


    【解决方案1】:

    好像你的 SQLData 只是一个辅助函数而不是 React 组件,我不知道你为什么要在里面使用状态,因为你可以直接返回结果return localArray;

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

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

    更新

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

    function importData() { 
        function runDemo() {
            console.log("hi");
        }
        return {
            runDemo: runDemo
        };
    }
    
    import SQLData from './components/SQLData';
    const data = SQLData();
    <CustomList data={data.runDemo()}/>
    

    或删除父函数,使所有函数都是独立的,这样原来的答案就可以了

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

    【讨论】:

    • 您好!感谢你的快速回复!所以我删除了 useState 等,基本上使 SQLData.js 成为一个充满帮助函数的文件,在 queryEmployeesSuccess 中我返回了'localArray;' .在 Apps.js 中,我也确实从 './components/SQLData' 导入了 SQLData; 。但是,由于某种原因,该函数没有在 SQLData.js 中被调用,因为我放了一个 alert("starting");函数 runDemo() 中的消息!我很好奇为什么会这样。再次感谢!
    • 能不能在return语句前调用一下
    • 所以我创建了一个 var 变量并调用它。但是,我收到的 _SQLData.default.runDemo 不是函数。导出默认函数 App() { var data=SQLData.runDemo();返回(); };
    • 我明白了,由于您尝试调用的函数在另一个函数内部,因此只能在父函数importData 内部访问,您需要将所有函数放在外部或返回函数。我更新了答案以反映这一点。
    【解决方案2】:

    你不会这样通过

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

    你必须像这样简单地通过

    <CustomList data={SQLData}/>
    

    因为 SQLData 会返回一些值。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-19
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 1970-01-01
        • 2014-12-27
        • 1970-01-01
        • 2020-01-01
        相关资源
        最近更新 更多