React:无法使用useContext挂钩



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

目录结构的Repo链接: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;

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

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

相关内容

  • 没有找到相关文章

最新更新