我正在使用 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);
}
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");
}
请注意,两个函数之间的唯一区别是参数名称:
msg
与 my_msg
。
在前端(使用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
很明显,第一行结果是执行了前端代码的第5行,但第二行是执行了第8行,因为第6行导致了错误。正如我们所看到的,Tauri 希望参数的名称为
myMsg
,而不是我在后端定义的 my_msg
。
发生了什么事?这正常吗?
来自 Tauri 指南中的传递命令参数,它说:
请注意,在 Rust 中使用蛇形命名法声明参数时,参数将转换为 JavaScript 的驼峰命名法。
所以这是Tauri故意做的。为什么?可能是遵循约定的最佳尝试(Rust 中首选 snake_case,而 Javascript 中首选 CamelCase)。
如果您不希望这样,您可以在定义命令时配置它:
#[tauri::command(rename_all = "snake_case")]
此外,请记住自动重命名仅影响参数名称,而不影响它们包含的数据。因此,外部名称将是camelCase,但任何嵌套字段都可能是snake_case(与Rust 侧匹配),除非您配置serde 通过
#[serde(rename_all = "camelCase")]
重命名它们。
相关: