2016-07-07 12 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, 
}; 

アプリケーション:

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

Counter成分にcomponentDidMountcomponentWillUnmountを追加することによって解決:

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> 
    ) 
    } 
}; 
関連する問題