Проблема с использование useReducer and useContext
При загрузке приложение выдает ошибку
Line 10:28: React Hook "useReducer" is called in function "counterState" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
Код приложения
App.js
import React, {Component, useContext} from 'react';
import logo from './logo.svg';
import './App.css';
import All from './All/All';
import {Route, Link} from 'react-router-dom';
import counterContext from './counterContext.js';
class App extends Component {
constructor () {
super();
this.state = {
counter: 'count',
but: 'but-main'
}
}
render () {
const {add, sub, ass, drop, count} = useContext(counterContext);
return (
<All>
<b className={this.state.counter}>{this.count}</b>
<button onClick={this.add} className={this.state.but}>Прибавить 1</button>
<button onClick={this.sub} className={this.state.but}>Вычесть 1</button>
<button onClick={this.ass} className={this.state.but}>Асинхронно добавить 100</button>
<button onClick={this.drop} className={this.state.but}>Сбросить к херам</button>
</All>
);
}
}
export default App
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {BrowserRouter} from 'react-router-dom';
import counterState from './counterState.js';
const application = (
<counterState>
<BrowserRouter>
<App/>
</BrowserRouter>
</counterState>
)
ReactDOM.render(application, document.getElementById('root'));
counterContext.js
import React, {createContext} from 'react';
const counterContext = createContext();
export default counterContext
counterState.js
import React, {useReducer} from 'react';
import {ADD, SUB, DROP, ASS} from './actionTypes';
import counterContext from './counterContext.js';
import counterReducer from './counterReducer.js';
const counterState = ({children}) => {
const initialState = {
count : 0
}
const [state, dispatch] = useReducer(counterReducer, initialState);
const add = () => {
dispatch({type: ADD})
}
const sub = () => {
dispatch({type: SUB})
}
const ass = (number) => {
dispatch({type: ASS})
}
const drop = () => {
dispatch({type: DROP, payload: 0})
}
const {count} = state;
return (
<counterContext.Provider value={{
add, sub, ass, drop, count
}}>
{children}
</counterContext.Provider>
);
}
export default counterState
counterReducer.js
import React from 'react';
import {ADD, SUB, DROP, ASS} from './actionTypes';
const counterReducer = (state, action) => {
switch(action.type) {
case ADD: return {
count: state.count + 1
}
case SUB: return {
count: state.count - 1
}
case ASS: return {
count: state.count + 100
}
case DROP: return {
count: action.payload
}
default: return state
}
}
export default counterReducer
I need some help!
Ответы (1 шт):
Автор решения: Konstantin Modin
→ Ссылка
counterState нужно писать с большой буквы если это компонент Реакт.
const СounterState = ({...}) => ...
<СounterState>
...
</СounterState>