因此,当我尝试在React上提交使用自定义挂钩的表单时,会出现以下错误:
未捕获(在promise中(类型错误:无法读取未定义的属性(读取"url"(在sendRequest(使用http.js:5:1(
在表单组件中,我有以下代码(由表单提交触发(
const enteredDateRef = useRef();
const enteredClientRef = useRef();
const enteredTaskRef = useRef();
const enteredTimeRef = useRef();
const renderNewTask = (data) => {
const taskData = {
id: data.name,
date: data.enteredDate,
client: data.enteredClient,
task: data.enteredTask,
time: data.enteredTime,
};
setTasks((tasks) => [taskData, ...tasks]);
};
const { sendRequest: postTask } = useHttp();
const submitTaskHandler = async (event) => {
event.preventDefault();
const newTaskData = {
Date: enteredDateRef.current.value,
Client: enteredClientRef.current.value,
Task: enteredTaskRef.current.value,
Time: enteredTimeRef.current.value,
};
postTask(
{
url: "https://myurl.com/myurl.json",
method: "POST",
body: JSON.stringify(newTaskData),
headers: { "Content-Type": "application.json" },
},
renderNewTask
);
};
这里是自定义挂钩:
const useHttp = (requestConfig, applyData) => {
const sendRequest = async () => {
const response = await fetch(requestConfig.url, {
method: requestConfig.method ? requestConfig.method : "GET",
headers: requestConfig.headers ? requestConfig.headers : {},
body: requestConfig.body ? JSON.stringify(requestConfig.body) : null,
});
const responseData = await response.json();
applyData(responseData);
};
return { sendRequest };
};
export default useHttp;
自定义挂钩用于http请求,显然在最后运行postTask时没有读取参数。为什么会发生这种情况,我该如何解决?
由于sendRequest
的定义没有任何参数,并且您没有将config传递给hook,因此即使将其传递给postTask
,requestConfig
也是undefined
。
您必须删除useHttp
挂钩的参数,并将其添加到挂钩内的sendRequest
函数中,如下所示
const useHttp = () => {
const sendRequest = async (requestConfig, applyData) => {
const response = await fetch(requestConfig.url, {
method: requestConfig.method ? requestConfig.method : "GET",
headers: requestConfig.headers ? requestConfig.headers : {}
body: requestConfig.body ? JSON.stringify(requestConfig.body) : null,
});
const responseData = await response.json();
applyData(responseData);
};
return { sendRequest };
};