标签:com create cas 维护 store 简洁 对象 export 参数
目标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) {
switch(action.type) {
case ‘INCREMENT‘:
return {
count: state.count + 1
};
case ‘DECREMENT‘:
return {
count: state.count - 1
};
default:
return state;
}
}
/**
/**
const App = () => (
<Provider store={store}>
<Counter/>
</Provider>
);
render(<App />, document.getElementById(‘root‘));
组件代码
import React from ‘react‘;
import { connect } from ‘react-redux‘;
/**
index.js创建的store全局对象,会注入到所有下级对象中,因此这里才可以使用dispatch函数来改变属性。
*/
class Counter extends React.Component {
increment = () => {
//实际上是调用全局store对象的dispatch函数
this.props.dispatch({ type: ‘INCREMENT‘ });
}
decrement = () => {
this.props.dispatch({ type: ‘DECREMENT‘ });
}
render() {
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement}>-</button>
<span>{this.props.count}</span>
<button onClick={this.increment}>+</button>
</div>
</div>
)
}
}
//具体的属性转换函数
function mapStateToProps(state) {
return {
count: state.count
};
}
//通过connect方法将store的state属性转换成本组件的属性
export default connect(mapStateToProps)(Counter);
标签:com create cas 维护 store 简洁 对象 export 参数
原文地址:https://blog.51cto.com/14623024/2453051