我有两个组件,一个是App组件,另一个是计数器组件。这里的App组件是根组件,计数器组件是子组件。我在这个应用程序中使用了redux。 在订阅方法的索引组件中,我正在接收更新的值。 这里的问题是Counter组件如果在redux存储中有任何变化,如何接收更新。?
//index.js
import React from 'react';
import { render } from 'react-dom';
import Counter from './Counter';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
const initialState = {
count: 0
}
function reducer(state=initialState,action) {
if(action.type === "INCREMENT"){
return [...state,{count: state.count + 1}]
}
if(action.type === "DECREMENT"){
return [...state,{count: state.count - 1}]
}
return state;
}
export const store = createStore(reducer);
store.subscribe(() =>{
console.log("state value",store.getState()[0].count);
})
const App = () => (
<Provider store={store}>
<Counter
/>
</Provider>
);
render(<App />, document.getElementById('root'));
--------------------------
//Counter.js
import React from 'react';
import { connect } from 'react-redux';
import {store} from './index';
class Counter extends React.Component {
increment(){
store.dispatch({type: 'INCREMENT',payload: 1})
}
decrement(){
store.dispatch({type: 'DECREMENT',payload: 1});
}
componentWillReceiveProps(){
console.log("Props",this.props)
}
render() {
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement.bind(this)}>-</button>
<span>{this.props.count}</span>
<button onClick={this.increment.bind(this)}>+</button>
</div>
</div>
)
}
}
const mapStateToProps = state => (
{count: state.count}
);
export default connect(mapStateToProps)(Counter);
答案 0 :(得分:0)
我想你不需要在reducer中返回一个数组,因为你的app的初始状态是object。你必须只是&#34;返回一个新对象&#34;。并且记住永远不要在减速器中改变状态,因为它被设计成纯粹的功能,意味着没有任何副作用。 您还需要在Counter组件中使用action dispatchers时添加mapDispatchToProps,以便connect(mapStateToProps,mapDispatchToProps)(Counter)