React Redux

Установка командою yarn add redux

// Для запуску поточного файлу виконати у консолі node redux
const redux = require('redux')

const initialState = {
    counter:0
}

// Reducer редуктор
const reducer = (state = initialState, action) => {

    if(action.type === 'ADD'){
        return {
            counter: state.counter + 1
        }
    }

    if(action.type === 'SUB'){
        return {
            counter: state.counter - 1
        }
    }

    if(action.type === 'ADD_NUMBER'){
        return {
            counter: state.counter + action.value
        }
    }

    return state

}

// Store Store зберігати
const store = redux.createStore(reducer)
// console.log('1',store.getState()); // Поточний станstore

// Підписуємось на оновлення store
store.subscribe(() => {
    console.log('Subscribe', store.getState())
})

// Actions дії
const addCounter = {
    type: 'ADD'
}

// Виклик дії
store.dispatch(addCounter)
// console.log('2', store.getState());

store.dispatch({type: 'SUB'})
// console.log('3', store.getState());

store.dispatch({type: 'ADD_NUMBER', value: 10})
// console.log('4', store.getState());

Зв'язуємо react та redux бібліотекою yarn add react-redux

Зміни до src/index.js

import {Provider} from 'react-redux'
import rootReducer from './redux/rootReducer'

const store = createStore(rootReducer)

const app = (
   <Provider store={store}>
        <App/>
    </Provider>
)

ReactDOM.render(app, document.getElementById('root'));

Вміст файлу './redux/rootReducer

const initialState = {
    counter:0
}

export default function rootReducer(state = initialState, action) {
    return state
} 

Підключення state до компоненту

import {connect} from 'react-redux'

//Перетворює параметри з state на параметри для роботи в компоненті
const mapStateToProps = (state) => {
    return {
        counter: state.counter
    }
}
export default connect(mapStateToProps)(App)

// Доступ до компоненту
{this.props.counter}

Поєднуємо кілька reducer

import {combineReducers} from 'redux'

import counter1 from './reducers/counter1'
import counter2 from './reducers/counter2'

export default combineReducers({
    counter1, counter2
}) 
2015-2026 © SumyNikNet