React Invalid hook call

先上一段異常錯誤信息html

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.3react

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版本的問題npm

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版本後就不報錯了,項目能正常運行。react-native

相關文章
相關標籤/搜索