我正在做一个GET取回请求,像这样:
let [responseData, setResponseData] = React.useState('');
const dispatch = useDispatch();
const fetchData = React.useCallback(() => {
let headers = new Headers({
'Content-Type': 'application/json',
});
fetch('http://localhost:3000/current_user', {
method: 'GET',
mode: 'cors',
headers: headers,
cache: 'no-cache',
redirect: 'follow',
referrer: 'no-referrer',
credentials: 'include',
})
.then(response => {
if (response.ok) return response.json();
throw new Error('Request failed.');
})
.then(data => {
setResponseData(data); // sent user data to redux
dispatch(props.setUser(data));
})
.catch(error => {
console.log(error);
});
}, []);
React.useEffect(() => {
fetchData();
}, [fetchData]);
但我想把所有的获取请求参数放在const中并在获取函数中调用const,像这样:
let [responseData, setResponseData] = React.useState('');
const dispatch = useDispatch();
const fetchData = React.useCallback(() => {
let headers = new Headers({
'Content-Type': 'application/json',
});
const reqParams = {
method: 'GET',
mode: 'cors',
headers: headers,
cache: 'no-cache',
redirect: 'follow',
referrer: 'no-referrer',
credentials: 'include',
}
fetch('http://localhost:3000/current_user', {
reqParams,
})
.then(response => {
if (response.ok) return response.json();
throw new Error('Request failed.');
})
.then(data => {
setResponseData(data); // sent user data to redux
dispatch(props.setUser(data));
})
.catch(error => {
console.log(error);
});
}, []);
React.useEffect(() => {
fetchData();
}, [fetchData]);
但是这不是一个成功的取回调用。我做错了什么,我不知道这里有什么错误。我怎样才能正确地编写这个函数
这不起作用,因为参数嵌套在reqParams
键下。
应该是
fetch('http://localhost:3000/current_user', reqParams)
注意
fetch('http://localhost:3000/current_user', {
reqParams,
})
与
相同fetch('http://localhost:3000/current_user', {
reqParams: {
method: 'GET',
mode: 'cors',
headers,
cache: 'no-cache',
redirect: 'follow',
referrer: 'no-referrer',
credentials: 'include',
}
})