1

我想知道如何从 React 功能组件外部调用方法。我编写了 GetUsedLockers() 函数,它获取所有使用过的储物柜并返回金额。现在我想从另一个组件(OrgLocker.tsx)调用这个函数,并在那里显示来自 getUsedLockers() 函数的数据。

OrgLockerTables.tsx

const OrgLockerTables: React.FC = () => {


    const lockerCall = 'lockers';
    const [lockerData, setLockerData] = useState({
        id: 0,
        guid: "",
        is_currently_claimable: false
    }[""]);

    useEffect(() => {
        componentConsole().then((res) => {
            setLockerData(res);
        })
        // eslint-disable-next-line   
    }, []);
    if (!lockerData) return (<div>Loading...</div>);


    //function to get all used lockers
    function getUsedLockers() {
        let amount = 0;

        for (let i = 0; i < lockerData.length; i++) {
            if (!lockerData.is_currently_claimable) {
                amount++;
            }
        }
        console.log('log from getusedlockers, amount: ', amount)
        return (amount)
    }


    // function to get JSON data from the API
    function componentConsole(): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            http.getRequest('/' + lockerCall).then((res) => {
                let data = res.data.data;

                console.log('data:', data);
                resolve(res.data.data);
            }).catch((error) => {
                console.log(error);
                reject();
            });
        })
    }
}

orgLocker.tsx

import OrgLockerTables from '../tables/orgLockerTables';

const OrgLockers: React.FC = () => {

    let lockerTable = new OrgLockerTables();

    return (
        <div className="main-div-org">
        <p>Used</p>
        <p>{lockerTable.getUsedLockers()}</p>
        </div>
    );
}

export default OrgLockers;

当尝试调用 OrgLockerTables 并将其存储在 lockerTable 中时,会出现以下错误:

预期 1-2 个参数,但得到 0.ts(2554)

任何帮助将不胜感激!

4

2 回答 2

2

我已经对所有内容进行了重组,使其更易于理解,我希望你不介意我认为你想要上面的评论。

locker-model.ts - 找到被回调的特定数据的类型

export type Locker = {
  id: number;
  guid: string;
  isCurrentlyClaimable: boolean;
}

locker-business.ts - 执行所有业务逻辑的地方,从数据调用到基于它的计算

import { Locker } from "./locker-models";

const lockerCall = 'lockers';

const mockedData: Locker[] = [{
  id: 0,
  guid: "sample",
  isCurrentlyClaimable: false,     
},
{
  id: 1,
  guid: "sample2",
  isCurrentlyClaimable: true,     
},
{
  id: 2,
  guid: "sample3",
  isCurrentlyClaimable: true,     
}]

// Mocked function from your backend (componentConsole where you use lockerCall variable)
export const getLockersData = (): Promise<Locker[]> => Promise.resolve(mockedData);

export const getAmount = (lockers: Locker[]): number => {
  let amount = 0;

  !!lockers ? 
    lockers.filter(({isCurrentlyClaimable}) => { if(isCurrentlyClaimable) amount++ })
    : 0;

  return amount;
};

index.tsx - 这两个组件都会调用以获取数据并呈现您正在寻找的结果

import React, { Component } from 'react';

import { Locker } from './locker-models';
import { getLockersData, getAmount } from './locker-business';

import './style.css';

type OrgLockersProps = {
  amount: number;
}

const OrgLockers: React.FC<OrgLockersProps> = ({ amount }) => {
  return (
    <div className="main-div-org">
      <p>Lockers used:</p>
      <p>{amount}</p>
    </div>
  );
}


type OrgLockerTableProps = {};

const OrgLockerTable : React.FC<OrgLockerTableProps> = props => {
    const [lockerData, setLockerData] = React.useState<Locker[]>([]);

    React.useEffect(() => {
      getLockersData().then(response => setLockerData(response));
    }, []);

    const amount = getAmount(lockerData);

    return (
      <div>
        <OrgLockers amount={amount} />
      </div>
    );
};

您可以在此处查看示例

于 2020-01-17T12:09:28.803 回答
0

您可以创建新的 .js 文件,如 Helpers.js 并使用参数定义导出函数

export function getUsedLockers(lockerData) {
    let amount = 0;

    //Check your loop it can be like that
    for (let i = 0; i < lockerData.length; i++) {
        if (!lockerData[i].is_currently_claimable) {
            amount++;
        }
    }
    console.log('log from getusedlockers, amount: ', amount)
    return (amount)
}

然后将其导入您要使用的地方。

import {getUsedLockers} from "../Helpers";

并像这样使用它:

const amount = getUsedLockers(data);
于 2020-01-17T11:31:32.227 回答