由于某种原因,Count
组件未收到状态更改。
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);
答案 0 :(得分:-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>
)
}
};