无法在提交回调/Shopify 北极星反应组件时获取表单中的更新值



问题摘要嗨团队, 我是北极星的新手,并尝试使用以下代码创建反应注册表单

import React, { useCallback, useState } from "react";
import {
Button,
Form,
FormLayout,
Layout,
Checkbox,
Card,
Page,
TextField,
} from "@shopify/polaris";
export const SignIn = () => {
const [textFieldValue, setTextFieldValue] = useState("Mark");
const [newsletter, setNewsletter] = useState(false);
const [email, setEmail] = useState("mark@hello.com");
const [password, setPassword] = useState("password");
const [loading, setLoading] = useState(false);
const handleNewsLetterChange = useCallback(
(value) => setNewsletter(value),
[]
);
const handleEmailChange = useCallback((value) =>{setEmail(value)}, [email]);
const handlePasswordChange = useCallback((value) => setPassword(value), [password]);
const handleTextFieldChange = useCallback(
(value) => setTextFieldValue(value),
[textFieldValue]
);
const handleSubmit = useCallback((_event) => {
// setLoading(true);
console.log(textFieldValue,newsletter,email, password  )
}, []);
const signupForm = (
<Form onSubmit={handleSubmit} preventDefault={true}>
{console.log(email)}
<FormLayout>
<TextField
label="Name"
value={textFieldValue}
onChange={handleTextFieldChange}
error={textFieldValue ? "" : "Name is required"}
/>
<TextField
value={email}
onChange={handleEmailChange}
label="Email"
type="email"
error={email ? "" : "Email is required"}
helpText={
<span>
We’ll use this email address to inform you on future changes to
Polaris.
</span>
}
/>
<TextField
value={password}
onChange={handlePasswordChange}
label="Password"
type="password"
error={password ? "" : "Password is required"}
helpText={
<span>
We’ll use this email address to inform you on future changes to
Polaris.
</span>
}
/>
<Checkbox
label="Sign up for the  newsletter"
checked={newsletter}
onChange={handleNewsLetterChange}
/>
<Button
submit
primary={true}
loading={loading}
fullWidth={true}
id="marketing-button"
>
Create your account
</Button>
</FormLayout>
</Form>
);
return (
<Page>
<Layout>  
<Layout.Section secondary>
<Card title="Signup" sectioned>
{signupForm}
</Card>
</Layout.Section>
</Layout>
</Page>
);
};

当 Onchange 所有值都得到更新时,但使用 onsubmit useCallback,我只得到使用 useState 分配的旧值,我尝试将 onsubmit 作为普通函数,如下所示的代码它的工作

const handleSubmit = () => {
console.log(textFieldValue,newsletter,email, password  )
}

预期行为由于我想将所有数据发送到API,请教我如何使用useCallback执行此操作,否则我可以使用正常的onSubmit函数

您错过了一些依赖项useCallback

const handleSubmit = useCallback((_event) => {
console.log(textFieldValue,newsletter,email, password  )
}, [textFieldValue,newsletter,email, password]);

相关内容

  • 没有找到相关文章

最新更新