Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

服务端渲染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的同构渲染问题

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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

AppWrapper 包一层,用 AppWrapper

<AppWrapper> <App /> </AppWrapper>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...