官网demo代码 https://github.com/reduxjs/redux/blob/master/examples/counter/src/index.js
目录结构
项目构建
cnpm init react-app myapp
cd myapp
npm start
```jsx //src/index.js import React from ‘react’ import ReactDOM from ‘react-dom’ import { createStore } from ‘redux’ import Counter from ‘./components/Counter’ import counter from ‘./reducers’
/**
- https://www.redux.org.cn/docs/api/createStore.html
- 传入reducer */ const store = createStore(counter) const rootEl = document.getElementById(‘root’)
const render = () => ReactDOM.render( <Counter /**
* getState
* https://www.redux.org.cn/docs/api/Store.html#getState
* 返回当前的state树
*/
value={store.getState()}
/**
* dispatch
* https://www.redux.org.cn/docs/api/Store.html#dispatch
* 派发action,改变state
*/
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>, rootEl )
render() /**
- subscribe
- https://www.redux.org.cn/docs/api/Store.html#subscribe
- 添加一个变化监听器。每当 dispatch action 的时候就会执行,
- state 树中的一部分可能已经变化。
- 你可以在回调函数里调用 getState() 来拿到当前 state。 */ store.subscribe(render) ```
//src/reducers/index.js
export default (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
//src/components/Counter.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class Counter extends Component {
constructor(props) {
super(props);
this.incrementAsync = this.incrementAsync.bind(this);
this.incrementIfOdd = this.incrementIfOdd.bind(this);
}
incrementIfOdd() {
if (this.props.value % 2 !== 0) {
this.props.onIncrement()
}
}
incrementAsync() {
setTimeout(this.props.onIncrement, 1000)
}
render() {
const { value, onIncrement, onDecrement } = this.props
return (
<p>
Clicked: {value} times
{' '}
<button onClick={onIncrement}>
+
</button>
{' '}
<button onClick={onDecrement}>
-
</button>
{' '}
<button onClick={this.incrementIfOdd}>
Increment if odd
</button>
{' '}
<button onClick={this.incrementAsync}>
Increment async
</button>
</p>
)
}
}
/**
* 不知道什么用删除了没感觉影响
*/
// Counter.propTypes = {
// value: PropTypes.number.isRequired,
// onIncrement: PropTypes.func.isRequired,
// onDecrement: PropTypes.func.isRequired
// }
export default Counter
点击按钮执行传递进来的onIncrement
onIncrement -> dispatch一个action到reducer中处理,处理后返回一个新的state,state被store的getState()获取赋值给value再传递到子组件Counter的value,数据更新,这是一个最简单的redux示例。