反应:无法使用useContext挂钩

时间:2020-08-13 21:16:51

标签: reactjs react-redux react-router react-hooks

由于某种原因,我无法使用 useContext 挂钩。

目录结构的回购链接:REPO URL

错误

未处理的运行时错误

错误:无效的挂钩调用。挂钩只能在功能组件的主体内部调用。发生这种情况可能是由于以下原因之一:

  1. 您可能使用了不匹配的React和渲染器版本(例如React DOM)
  2. 您可能正在违反挂钩规则
  3. 您可能在同一应用中拥有多个React副本

我的代码:

上下文

import { createContext, useReducer } from 'react'
export const DataContext = createContext();

const DataProvider = ({ intialState, reducer, children }) => {
    <DataContext.Provider value={useReducer(reducer, intialState)}>
        {children}
    </DataContext.Provider >
}

export default DataProvider;

减速器:

import { types } from './types';

export const initialState = {
    name: '',
    room: ''
}

const reducer = (state, action) => {
    console.log("Calling action", action);
    switch (action.type) {
        case types.SET_NAME:
            return { ...state, name: action.name }
        case types.SET_ROOM:
            return { ...state, name: action.room }
        default:
            return state;
    }
}

引起问题的主要组件:

import { useContext } from 'react';
import { input } from '../hooks/input';
import Link from 'next/link';
import { DataContext } from '../context/DataProvider';
import { types } from '../reducers/types';

const Join = () => {
    const [name, setName] = input('');
    const [room, setRoom] = input('');

    const submit = () => {
        console.log('FORM');
        const [state, dispatch] = useContext(DataContext);
        dispatch({
            type: types.SET_NAME,
            name
        });
        dispatch({
            type: types.SET_ROOM,
            room
        })
    }
    return (
        <div>
            <h1>Join</h1>

            <input onChange={(e) => setName(e)} placeholder="name" />
            <input onChange={(e) => setRoom(e)} placeholder="room" />
            <Link href="/chat">
                <button type="submit" onClick={() => submit()}>Submit</button>
            </Link>

        </div>
    )
}

export default Join;

1 个答案:

答案 0 :(得分:1)

您只能在功能组件的主体中使用钩子。您不能在回调函数中使用它们。因此,将useContext的使用移出提交:

const [state, dispatch] = useContext(DataContext);
const submit = () => {
  console.log("FORM");
  dispatch({
    type: types.SET_NAME,
    name,
  });
  dispatch({
    type: types.SET_ROOM,
    room,
  });
};