Rust、Tauri:为什么 tauri 会修改调用函数的组合参数名称?

问题描述 投票:0回答:1

我使用 Tauri 构建 GUI。 在我的后端,我定义了两个将在前端调用的函数:

#[tauri::command]
fn functional_test(msg: String){
    println!("Received : {}", msg);
}

#[tauri::command]
fn no_functional_test(my_msg: String){
    println!("Received : {}", my_msg)
}

请注意,两个函数之间的区别在于参数名称:msgmy_msg

基本上,我有这部分代码来初始化tauri:

fn main() {
    tauri::Builder::default()
        .setup(...)
        .invoke_handler(tauri::generate_handler![functional_test, no_functional_test])
        .run(tauri::generate_context!())
        .expect("failed to run app");
}

在前端(使用React),我在所有这些代码块中都有:

export function AComponent({name}: {name: string}){

    useEffect(() => {
        const fetchSomething = async () => {
            try {
                await invoke('functional_test', {msg:"This is a message"})
                await invoke('no_functional_test', {my_msg:"This is also a message"})

            } catch (error) {
                await invoke('functional_test', {msg:error})
            }
        };

        fetchSomething();
    }, [name]);

    return (...)
}

这里发生了什么:我尝试调用这两个函数中的每一个。 因为不知道如何显示前端的日志,所以使用功能函数来调试。

有输出:

Received : This is a message
Received : invalid args `myMsg` for command `no_functional_test`: command no_functional_test missing required key myMsg

显然,第一行结果是执行了前端代码的第6行,但是第二行是执行了第10行,因为第7行导致了错误。

正如我们所见,tauri 希望参数的名称为 myMsg,而不是我在后面定义的 my_msg

所以这是我的问题:发生了什么事?这是正常的吗?是否有任何文档或其他线程处理此问题,特别是原因?

rust tauri
1个回答
0
投票

来自 Tauri 指南中的传递命令参数,它说:

请注意,在 Rust 中使用蛇形命名法声明参数时,参数将转换为 JavaScript 的驼峰命名法。

所以这是Tauri故意做的。为什么?可能是遵循约定的最佳尝试(Rust 中首选 snake_case,而 Javascript 中首选 CamelCase)。

如果您不希望这样,您可以在定义命令时配置它:

#[tauri::command(rename_all = "snake_case")]

另外,请记住,这只会影响参数名称,而不影响它们包含的数据。因此,外部名称将是camelCase,但任何嵌套字段都可能是snake_case(与Rust 侧匹配),除非您配置serde 通过

#[serde(rename_all = "camelCase")]
重命名它们。

相关:

© www.soinside.com 2019 - 2024. All rights reserved.