2016-07-07 4 views
-1

Компонент Count по каким-либо причинам не принимает изменений в состоянии.redux компонент не обновляется

index.js:

import React from 'react'; 
import { render } from 'react-dom'; 
import configureStore from './store/configureStore.js'; 
import { Root } from './containers/Root/index.jsx'; 

render(
    <Root store={configureStore()} />, 
    document.getElementById('root') 
); 

Корень:

import React from 'react'; 
import { Provider } from 'react-redux'; 
import { App } from '../App/index.jsx'; 

export const Root = (
    props 
) => { 
    const { store } = props; 

    return (
    <div> 
     <Provider store={store}> 
     <App /> 
     </Provider> 
    </div> 
); 
}; 
Root.propTypes = { 
    store: React.PropTypes.object.isRequired, 
}; 

App:

import React, { PropTypes } from 'react'; 
import Count from '../../components/Count/index.jsx'; 
import { Buttons } from '../../components/Buttons/index.jsx'; 

export const App =() => { 
    return (
    <div> 
     <Count /> 
     <Buttons /> 
    </div> 
); 
}; 

Количество:

import React, { Component, PropTypes } from 'react'; 

export default class Count extends Component{ 
    render(){ 
    const { store } = this.context; 
    const count = store.getState(); 

    return (
     <h1>{count}</h1> 
    ) 
    } 
}; 
Count.contextTypes = { 
    store: PropTypes.object, 
}; 

Кнопки:

import React, { PropTypes } from 'react'; 
import { connect } from 'react-redux'; 
import { dec, inc } from '../../actions/incrementDecrement'; 

const ButtonsList = ({ 
    count, 
    decHandler, 
    incHandler 
}) => (
    <div> 
    <button 
     onClick={() => decHandler(count)} 
    > 
     - 
    </button> 
    <button 
     onClick={() => incHandler(count)} 
    > 
     + 
    </button> 
    </div> 
); 
ButtonsList.propTypes = { 
    count: PropTypes.number.isRequired, 
    incHandler: PropTypes.func.isRequired, 
    decHandler: PropTypes.func.isRequired, 
}; 

const mapStateToProps = (state) => { 
    return { 
    count: state, 
    } 
}; 

const mapDispatchToProps = (dispatch) => { 
    return { 
    decHandler: (count) => { 
     dispatch(dec(count)); 
    }, 
    incHandler: (count) => { 
     dispatch(inc(count)); 
    } 
    }; 
}; 

export const Buttons = connect(
    mapStateToProps, 
    mapDispatchToProps 
)(ButtonsList); 

ответ

-1

решена путем добавления componentDidMount и componentWillUnmount к Counter компонента:

export default class Count extends Component{ 
    componentDidMount() { 
    const { store } = this.context; 
    this.unsubscribe = store.subscribe(() => 
     this.forceUpdate() 
    ); 
    } 

    componentWillUnmount() { 
    this.unsubscribe(); 
    } 

    render(){ 
    const { store } = this.context; 
    const count = store.getState() 

    return (
     <h1>{count}</h1> 
    ) 
    } 
}; 
Смежные вопросы