服务端渲染react-redux 报错 Invalid hook call. Hooks can only be called

\#\#\# 问题描述
server error Error: 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.

\#\#\# 问题出现的环境背景及自己尝试过哪些方法

\#\#\# 相关代码
排查了很久,预计是redux的connect执行的时候就报错了

import { connect } from 'react-redux'
import { toggleTodo, VisibilityFilters } from '../redux/actions'
import TodoList from '../components/TodoList'

const getVisibleTodos = (todos, filter) => {
    switch (filter) {
        case VisibilityFilters.SHOW_ALL:
            return todos
        case VisibilityFilters.SHOW_COMPLETED:
            return todos.filter(t => t.completed)
        case VisibilityFilters.SHOW_ACTIVE:
            return todos.filter(t => !t.completed)
        default:
            throw new Error(`Unknown filter: ${filter}`)
    }
}

const mapStateToProps = state => ({ todos: getVisibleTodos(state.todos, state.filter) })

const mapDispatchToProps = (dispatch) => {
    return {
        onTodoClick: (index, completed) => {
            dispatch(toggleTodo(index, completed))
        }
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(TodoList)

\#\#\# 你期待的结果是什么?实际看到的错误信息又是什么?
git 代码下载:https://gitee.com/zhujierong/...

客户端运行:npm i dev:client 访问:http://localhost:3030/
服务端运行:npm i dev:nodemon 访问:http://localhost:3031/

如何解决服务端使用Redux的同构渲染问题

问题已解决:解决方法看这里

阅读 4.7k
2 个回答

react hooks 必须放在函数组件内
再检查一下自己的 TodoList 组件是否写错了呢。
gitte 没有权限访问

更新:————————————

 const AppWrapper = ({ children }) => {
        const store = createStore(reducer);

        return (<Provider store={store}>{children}</Provider>);
    }

AppWrapper 包一层,用 AppWrapper

<AppWrapper> <App /> </AppWrapper>

总之就是 createStore 得放在组件函数里边

刚刚我在 server端的入口文件中增加了babel的 @babel/register支持了ES6,调整了入口文件server-entry.js(里面是React代码)缓存读取变成了require引入。现在可以了进行服务端渲染了。

但还是不知道问题的根本原因。
现在感觉就是 server-entry.js 文件里面的React代码的编译问题,增加ES6的支持使得server-entry.js得到编译。

还是希望有朋友帮忙看下问题的根本原因

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏