在RecoilJS
文档中,有一个如何处理异步数据查询的example,但它只是关于获取数据。
假设我有一个简单的状态:
const accountState = atom({
key: "accountState",
default: {
id: "",
name: "",
}
});
还有一个作为注册表单的组件:
const RegisterForm = () => {
return (
<form>
<input type="text" name="username" />
<button type="submit">Register</button>
</form>
)
}
发布的数据在 FormData
中。成功创建新帐户后,服务器将发送一个包含帐户的id
和name
的响应。
{
"id": "abcdef123456",
"name": "example"
}
此响应数据将被设置为 accountState
的新状态。
如何在 RecoilJS
中处理这个过程?
最佳答案
您可以只处理 http 请求并将响应设置为状态。
const RegisterForm = () => {
const [account, setAccount] = useRecoilState(accountState);
const handleSubmit = async e => {
e.preventDefault();
const response = await fetch(url, {
method: 'POST',
body: data,
});
const responseJson = await response.json();
setAccount(responseJson);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="username" />
<button type="submit">Register</button>
</form>
);
}
编辑
为了有一个可重用的方法,我建议构建自定义钩子(Hook)以供频繁使用
const useRegister = () => {
const setAccount = useSetRecoilState(accountState);
const register = useCallback(async (username)=> {
const response = await fetch(url, {
method: 'POST',
body: { username },
});
const responseJson = await response.json();
setAccount(responseJson);
}, [setAccount]);
return register;
}
const RegisterForm = () => {
const register = useRegister();
const handleSubmit = async e => {
e.preventDefault();
await register(username);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="username" />
<button type="submit">Register</button>
</form>
);
}
关于reactjs - 使用 RecoilJS 通过 API 发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62832167/