【问题标题】:React: Unable to use useContext hook反应:无法使用 useContext 钩子
【发布时间】:2020-12-03 18:48:45
【问题描述】:

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

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

错误

未处理的运行时错误

错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一:

  1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  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;

【问题讨论】:

  • const [state, dispatch] = useContext(DataContext); 这是您的问题行。正如错误所说:您只能在函数组件的 body 中使用钩子。这是在普通函数中使用的,而不是在函数组件主体中使用,因此是不允许的(参见规则 2)。

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


【解决方案1】:

你只能在函数组件的主体中使用钩子。您不能在回调函数中使用它们。所以将 useContext 的使用移到提交之外:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 2020-10-20
    • 1970-01-01
    • 2020-02-20
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多