如何解决使用 Axios 使用 Formik 发布数据时的挂钩调用无效
总结问题
我的代码的目标是将表单数据发布到我的 REST API:/api/profiles/<:id>。
我使用 Formik 处理所有需要用表单完成的工作,并使用 axios 获取当前用户的 id 然后填写正确的 REST API url,以及执行对该 REST API 的 POST 请求。实际结果是一条错误消息,指出我使用了无效的钩子调用。这是错误的图片:
描述您尝试过的内容
我去了 React 网站,那里提到了几种调试情况的方法:https://reactjs.org/warnings/invalid-hook-call-warning.html
我发现我写的代码实际上有两份 react 包。因此,我转到此堆栈溢出以查看如何修复它:Duplicate ReactJS import issue when using npm link to test component before publishing as npm package 但是当我按照接受的答案进行操作时,我收到一条错误消息,指出该操作被我的操作系统 (macOS) 拒绝。接受的答案还谈到拥有一个本地图书馆,但我认为我从未使用过它,所以我觉得我的问题的解决方案在于我的代码中的某处。
postText: Yup.string().required("required"),message: Yup.string().required("required")
});
function getProfile(){
const [profiles,setProfiles] = useState([])
useEffect(() => {
const p = getProfile(window.REP_LOG_APP_PROPS.user_id)
const api = axios.create({
baseURL: 'http://127.0.0.1:8000/api/profiles/' + p.id
})
axios.get(api)
.then(res =>{
console.log(res)
setProfiles(res.data)
})
.catch(err => {
console.log(err)
})
},[])
return (
profiles
)
}
export default function CreatePost() {
/* Server State Handling */
const [serverState,setServerState] = useState();
const handleServerResponse = (ok,msg) => {
setServerState({ok,msg});
};
const p = getProfile(window.REP_LOG_APP_PROPS.user_id)
const api = axios.create({
baseURL: 'http://127.0.0.1:8000/api/profiles/' + p.id
})
const handleOnSubmit = (values,actions) => {
axios({
method: "POST",url: api,data: values
})
.then(response => {
actions.setSubmitting(false);
actions.resetForm();
handleServerResponse(true,"Thanks!");
})
.catch(error => {
actions.setSubmitting(false);
handleServerResponse(false,error.response.data.error);
});
};
return (
<div>
<h1>Create a Post</h1>
<Formik
initialValues={{ postText: "Post something inspiring..."}}
onSubmit={handleOnSubmit}
validationSchema={formSchema}
>
{({ isSubmitting }) => (
<Form id="fs-frm" novalidate>
<label htmlFor="postText">This is the label here</label>
<Field id="postText" name="postText" component="textarea" />
<ErrorMessage name="postText" className="errorMsg" component="p" />
<button type="submit" disabled={isSubmitting}>
Post
</button>
{serverState && (
<p className={!serverState.ok ? "errorMsg" : ""}>
{serverState.msg}
</p>
)}
</Form>
)}
</Formik>
</div>
);
};```
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。