簡體   English   中英

Uncaught TypeError: create is not a function using useEffect React Hook with AJAX 請求

[英]Uncaught TypeError: create is not a function using useEffect React Hook with AJAX request

我正在嘗試使用 React hooks 獲取一些數據並顯示它,但出現錯誤:

 function App() { const [user, setUser] = React.useState(null); React.useEffect(fetch('https://randomuser.me/api/').then(results => results.json()).then(data => { setUser(data.results[0]); }), []); return <div> {user? user.name.first: 'Loading...'} </div>; } ReactDOM.render(<App/>, document.getElementById('app'));
 <script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script> <div id="app"></div>

Uncaught TypeError: create is not a function
    at commitHookEffectList (react-dom.development.js:15901)
    at commitPassiveHookEffects (react-dom.development.js:15911)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at commitPassiveEffects (react-dom.development.js:17299)
    at wrapped (scheduler-tracing.development.js:204)
    at flushPassiveEffects (react-dom.development.js:17338)
    at dispatchAction (react-dom.development.js:12035)
    at eval (index.jsx? [sm]:9)

這是因為沒有回調函數傳遞給useEffect 在上面的示例中,它實際上是在執行fetch請求,該請求不返回任何內容。 fetch調用包裝在箭頭/匿名函數中,它將起作用。

 function App() { const [user, setUser] = React.useState(null); React.useEffect(() => { // Pass in a callback function! fetch('https://randomuser.me/api/') .then(results => results.json()) .then(data => { setUser(data.results[0]); }); }, []); return <div> {user ? user.name.first : 'Loading...'} </div>; } ReactDOM.render(<App/>, document.getElementById('app')); 
 <script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script> <div id="app"></div> 

useEffect 必須有回調 function。在這種情況下,您可以在括號內使用箭頭/匿名 function。 useEffect(()=>{your code})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM