嵌套函数中第二个函数不工作



我创建了一个useState钩子来存储从第一个函数获取的ID。,钩子的初始值是一个空字符串('')。但问题是,当我保存文件两次时,钩子会存储我获取的ID,否则它将完全为空。

const [loading, setLoading] = useState(true);
const [data, setData] = useState([]);
const [id, setId] = useState(' ');
const getCMSID = () => {
let url = `${URL}/store-api/category`;
let getId = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'sw-access-key': `${API_KEY}`,
},
};
fetch(url, getId)
.then(res => res.json())
.then(json => setId(json.elements[0].cmsPageId))
.catch(err => console.error('error:' + err));
const getCMSPage = () => {
const cmsUrl = `${URL}/store-api/cms/${id}`;
let getcms = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'sw-access-key': `${API_KEY}`,
},
};
fetch(cmsUrl, getcms)
.then(res => res.json())
.then(json => {
setData(json.sections);
setLoading(false);
})
.catch(err => console.error('Error:' + err));
};
getCMSPage();
};
useEffect(() => {
getCMSID();
}, []);

我得到了解决方案,它有效。

const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
const getCMSID = () => {
let url = `${URL}/store-api/category`;
let getId = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'sw-access-key': `${API_KEY}`,
},
};
fetch(url, getId)
.then(res => res.json())
.then(json => {
getCMSPage(json.elements[0].cmsPageId);
})
.catch(err => console.error('error:' + err));
const getCMSPage = gId => {
const cmsUrl = `${URL}/store-api/cms/${gId}`;
let getcms = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'sw-access-key': `${API_KEY}`,
},
};
fetch(cmsUrl, getcms)
.then(res => res.json())
.then(json => {
setData(json.sections);
setLoading(false);
})
.catch(err => console.error('Error:' + err));
};
};
useEffect(() => {
getCMSID();
}, []);

@creditNayeem M. Muzahid

useState 钩子是异步的。所以不要用useState来设置并在同一函数中使用。根据您的代码,您可以直接使用ID而不使用设置值。

const [loading, setLoading] = useState(true);
const [data, setData] = useState([]);
const [id, setId] = useState(' ');
const getCMSID = () => {
let url = `${URL}/store-api/category`;
let getId = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'sw-access-key': `${API_KEY}`,
},
};
fetch(url, getId)
.then(res => res.json())
.then(json => { return setId(json.elements[0].cmsPageId)})
.catch(err => console.error('error:' + err));
const getCMSPage = () => {
const cmsUrl = `${URL}/store-api/cms/${globalID}`;
let getcms = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'sw-access-key': `${API_KEY}`,
},
};
fetch(cmsUrl, getcms)
.then(res => res.json())
.then(json => {
setData(json.sections);
setLoading(false);
})
.catch(err => console.error('Error:' + err));
};
getCMSPage();
};
useEffect(() => {
getCMSID();
}, []);

如果需要,可以在函数外部使用钩子的值。

最新更新