React Invalid hook call


先上一段異常錯誤信息

Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
    .............

最近在寫一個同構渲染的react代碼,但是在運行react代碼時遇到了上述的錯誤,服務端render組建的代碼如下,我package中react和react-dom的版本為16.6.3

export const render = (req) => {

  const reduce = (state = {name: 'naruto'}, action) => {
    return state;
  }
  const serverStore = createStore(reduce);
  
  const content = renderToString((
    <Provider store={serverStore}>
      <StaticRouter location={req.path} context={{}}>
        {Routes}
      </StaticRouter>
    </Provider>
  ));
  return `<html>
    <head>
      <title>ssr</title>
    </head>
    <body>
      <div id='root'>${content}</div>
    </body>
    <script src='/index.js'></script>
  </html>`
}

在異常提示信息中有一個鏈接https://fb.me/react-invalid-hook-call,打開后發現是react版本的問題

Mismatching Versions of React and React DOM
You might be using a version of react-dom (< 16.8.0) or react-native (< 0.59) that doesn’t yet support Hooks. You can run npm ls react-dom or npm ls react-native in your application folder to check which version you’re using. If you find more than one of them, this might also create problems (more on that below).

升級最新react和react-dom版本后就不報錯了,項目能正常運行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM