由于某种原因,我无法使用 useContext 挂钩。
目录结构的回购链接:REPO URL
错误:
未处理的运行时错误
错误:无效的挂钩调用。挂钩只能在功能组件的主体内部调用。发生这种情况可能是由于以下原因之一:
我的代码:
上下文:
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;
答案 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,
});
};