我似乎無法將 javascript 中此 API 呼叫的值回傳給我的反應組件。我有一個呼叫 API 的 java 腳本檔案。在js檔案中,回傳結果但是當我在我的react組件中呼叫useEffect中的js函式時,它回傳undefined。
export function ordersData() {
const partner_code = localStorage.getItem('partner_code')
let items = []
let data = []
let isLoaded = false
let error = ''
fetch('xxxxxxxxxxxx' process.env.REACT_API)
.then(res => res.json())
.then((result) => {
for (let instance in result['docs']) {
let payload = (result['docs'][instance])
payload.id = instance
payload.timestamp = shortMonthYear(payload.timestamp)
data.push(payload)
}
items = data.reverse()
}, (err) => {
isLoaded(true)
error(err)
})
}
這是我的 rect 組件
匯出默認函式 OrdersChart() {
const [payload, setPayload] = useState([])
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
setPayload = ordersData()
console.log(payload)
}, [])
…………
變數有效載荷為空
uj5u.com熱心網友回復:
您需要使用 React 鉤子進行 API 呼叫并存盤資料。您可以使用useEffect鉤子呼叫 API 并useState用于在狀態中存盤資料。
const { useState } = React;
function useFetchData() {
const [loading, setLoading] = React.useState([]);
const [data, setData] = React.useState([]);
React.useEffect(() => {
setLoading(true);
fetch("https://randomuser.me/api/?results=10")
.then((response) => response.json())
.then((responseJson) => {
setData(responseJson.results);
setLoading(false);
})
.catch((error) => {
console.error(error);
setLoading(false);
});
}, []);
return { loading, data };
}
function App() {
const { loading, data } = useFetchData();
if(loading){
return <p>Loading... </p>
}
return (
<div>
{data.map((item) => (
<div>{item.name.first}</div>
))}
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
uj5u.com熱心網友回復:
我發現的最干凈的方法是這個
將父組件更改為此
useEffect(() => {
newFunctionName();
}, [])
async function newFunctionName(){
const response = await ordersData();
console.log(response)
// you can then set all your states directly in here
}
將 api 呼叫組件更改為此。
export default async function ordersData() {
try{
const res = await fetch('xxxxxxxxxxxx' process.env.REACT_API)
return res
} catch(err){
console.log(err)
return(err)
}
}
現在您在父組件中有回應,并且可以從那里設定狀態。
uj5u.com熱心網友回復:
您不會在此函式中回傳任何內容。您只需在資料中推送有效負載值,即區域變數。您可以通過 setState 使用 state 和 set value。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339889.html
標籤:javascript 反应 接口 拿来
