当前位置 : 主页 > 网页制作 > React >

React Invalid hook call

来源:互联网 收集:自由互联 发布时间:2021-06-15
先上一段异常错误信息 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 a

先上一段异常错误信息

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版本后就不报错了,项目能正常运行。

网友评论