npm install redux
Store буде керувати нашими данними.
import { createStore } from 'redux';
const store = createStore();
Описуємо ф-цію, яка буде змінювати state.
const counterReducer = (state = { counter: 0 }, action) => {
return {
counter: state.counter + 1,
};
};
const store = createStore(counterReducer);
Який реагуватиме на зміни в State.
store.subscribe(() => {
const latestState = store.getState();
console.log('>>>', latestState);
});
Змінюємо стан.
store.dispatch({ type: 'increment' });
const counterReducer = (state = initState, action) => {
if (action.type === 'increment') {
return { counter: state.counter + 1 }
}
if (action.type === 'decrement') {
return { counter: state.counter - 1 }
}
return state;
}
Ми можемо розділяти ред'юсери на дрібніші функції, кожна з яких керуватиме своєю частиною стану.
const store = createStore(combineReducers({
counter: counterReducer,
movies: moviesReducer,
}));
npm install react-redux - встановлюємо пакет
import { Provider } from 'react-redux';
import { store } from './store';
<Provider store={store}>
<App/>
</Provider>
Підключаємо наш компонент до стору..
Дозволяє отримати дані з Redux-стору за допомогою селектора.
import { useSelector } from 'react-redux';
const counter = useSelector((state) => state.counter);
Цей хук повертає посилання на функцію dispatch із Redux, що дозволяє нам ініціювати зміни в сторі.
const dispatch = useDispatch();
const onClickPlus = () => dispatch({ type: 'increment' });
const onClickMinus = () => dispatch({ type: 'decrement' });
Функція connect підключає класовий компонент до стору та передає їх у пропси.
const mapStateToProps = (state) => ({ counter: state.counter });
const mapDispatchToProps = (dispatch) => ({
increment: () => dispatch({ type: 'increment' }),
decrement: () => dispatch({ type: 'decrement' }),
});
export default connect(mapStateToProps, mapDispatchToProps)(Counter)