未捕获的TypeError:使用useEffect React Hook和AJAX请求创建的函数不是

时间:2018-11-11 06:18:40

标签: javascript reactjs react-hooks

我正在尝试使用React钩子来获取一些数据并显示它们,但出现错误:

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)

1 个答案:

答案 0 :(得分:2)

这是因为没有回调函数传递到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>