@narciso
Изменение состояния в Redux с помощью React-Redux можно сделать следующим образом:
1
|
const incrementCounter = () => ({ type: 'INCREMENT_COUNTER' }) |
1 2 3 4 5 6 7 8 9 10 |
const initialState = { counter: 0 } const counterReducer = (state = initialState, action) => { switch (action.type) { case 'INCREMENT_COUNTER': return { ...state, counter: state.counter + 1 } default: return state } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import { useDispatch } from 'react-redux' const Counter = () => { const dispatch = useDispatch() const handleClick = () => { dispatch(incrementCounter()) } return ( <div> <p>Counter: {counter}</p> <button onClick={handleClick}>Increment</button> </div> ) } |
1 2 3 4 5 6 7 |
import { useSelector } from 'react-redux' const Counter = () => { const counter = useSelector(state => state.counter) // ... } |
Обратите внимание, что использование функций useDispatch и useSelector требует, чтобы ваш компонент был внутри компонента Provider, который был настроен для работы с хранилищем Redux.
@narciso
Перед использованием React-Redux вам потребуется установить библиотеку react-redux и redux. Для начала создайте файл store.js, который будет объединять все ваши редукторы(reducers) и создавать store.
Пример store.js:
1 2 3 4 5 6 7 8 9 10 |
import { createStore, combineReducers } from 'redux';
import counterReducer from './reducers/counterReducer';
const rootReducer = combineReducers({
counter: counterReducer
});
const store = createStore(rootReducer);
export default store;
|
Теперь необходимо обернуть ваше приложение в компонент <Provider> из библиотеки react-redux и указать созданный store.
Пример index.js:
1 2 3 4 5 6 7 8 9 10 11 12 |
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
|
Далее, создайте редуктор, который будет обрабатывать действия для изменения состояния вашего приложения.
Пример counterReducer.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const initialState = {
counter: 0
};
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT_COUNTER':
return { ...state, counter: state.counter + 1 };
default:
return state;
}
};
export default counterReducer;
|
Теперь вы можете использовать хуки useDispatch и useSelector в ваших функциональных компонентах, чтобы получить доступ к диспетчеру и текущему состоянию ваших редукторов.
Пример Counter.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
const Counter = () => {
const counter = useSelector(state => state.counter);
const dispatch = useDispatch();
const handleIncrement = () => {
dispatch({ type: 'INCREMENT_COUNTER' });
};
return (
<div>
<p>Counter: {counter}</p>
<button onClick={handleIncrement}>Increment</button>
</div>
);
};
export default Counter;
|
Теперь при клике на кнопку "Increment" будет вызываться действие INCREMENT_COUNTER, которое изменит состояние вашего приложения и обновит компонент Counter.