@DaveGarrow

Как получить state из redux store?

Как получить state chosenAddress во втором компоненте, предварительно изменяя его в первом? Крашится с ошибкой что getState is not a function. Что не так?

Есть index.js, где в rootReducer импортирую registrationReducer ------------------------------------
import {createStore, compose, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import rootReducer from './store/reducers/rootReducer';

const store = createStore(
  rootReducer
)

store.subscribe(() => {
  console.log('Subscribe', store.getState());
})

Есть reducer ------------------------------------
const initialState = {
    chosenAddress: '',
}

export default function registartionReducer(state = initialState, action) {
    switch (action.type) {
        case 'changeAddress':
            return {
                ...state,
                chosenAddress: action.value,
            }
        default:
            return state
    }
}

Есть action ------------------------------------
export function changeAddress(payload) {

    return {
        type: 'changeAddress',
        value: payload
    }
}

Есть компонент #1 у которого есть метод linkClick (state меняется, это отрабатывает) ------------------------------------
import { connect } from 'react-redux';
import { changeAddress } from "../store/actions/changeRegistration";

class Component1 extends React.Component {
	constructor(props) {
        super(props);

        this.state = {
            chosenAddress: '',
        }
    }

    linkClick() {
        console.log(this.state.chosenAddress);
        this.props.changeAddressAction(this.state.chosenAddress);
    }

	render() {
        ...
    }
}

const mapStateToProps = (state) => {
    return {
        chosenAddress: state.settingsReducer.chosenAddress,
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        changeAddressAction: value => dispatch(changeAddress(value)),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Component1);

Есть компонент 2 (тут и ошибка)------------------------------------
import registartionReducer from '../store/reducers/registration.js';

class Component2 extends React.Component {

    componentDidMount() {
        console.log(registartionReducer.getState().chosenAddress);
    }
    
	render() {
        ...   
    }
}

export default Component2;
  • Вопрос задан
  • 697 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы