调用函数 - React Native SDK
Atlas Device SDK 已弃用。 有关详细信息,请参阅弃用页面。
本部分中的示例演示了如何调用名为 sum
的简易函数,该函数接受两个参数并将它们相加,然后返回结果:
// sum: adds two numbers exports = function(a, b) { return a + b; };
开始之前
在 App Services App 中,定义 Atlas Function。
在客户端项目中,初始化 App 客户端。
然后,在 React Native 项目中对用户进行身份验证。
调用函数
重要
使用函数时,确保对客户端数据进行清理,以防止代码注入。
要调用函数,可以将其名称和参数传递给 User.callFunction(),或者像调用 User.functions 属性上的方法一样调用该函数。
import React from 'react'; import {useUser} from '@realm/react'; function Addition() { // Get currently logged in user const user = useUser(); const addNumbers = async (numA: number, numB: number) => { // Call Atlas Function // Method 1: call with User.callFunction() const sumMethod1 = await user?.callFunction('sum', numA, numB); // Method 2: Call with User.function.<Function name>() const sumMethod2 = await user?.functions.sum(numA, numB); // Both methods return the same result console.log(sumMethod1 === sumMethod2); // true }; // ... }