Redux学习【store】
eg:代表代码对照
若文章有误,欢迎读者指出
配置store
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
import {createStore} from 'redux'
const defaultState = { num: 0 }
const reducer = (state = defaultState, actions) => { if (actions.type == 'addHandle') { return {num: actions.add + state.num} } return state }
const store = createStore(reducer) export default store
|
ReduxDemo.jsx代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import React, { Component } from 'react'
import store from '../store/index' export default class ReduxDemo extends Component { constructor(props) { super(props) this.state = store.getState() store.subscribe(() => { this.setState(() => store.getState()) }) } handleClick = () => { const userActions = { type: 'increhander', incre: 1 } store.dispatch(userActions) } render() { return ( <div> <h3>redux使用</h3> <p>{this.state.num}</p> <button onClick={this.handleClick}>+1</button> </div> ) } }
|
store已经挂载在全局了,然后我们页面中现在如何使用?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import React, { Component } from 'react' import { connect } from 'react-redux'
class ReduxDemo1 extends Component { render() { return ( <div> <h3>redux使用</h3> <p>{ this.props.mynum }</p> <button onClick={ this.props.increseFun }>+2</button> </div> ) } }
const mapStateToProps = (state) => { return{ mynum:state.num } }
const mapDispatchToProps = (dispatch) => { return{ increseFun(){ const myAction = { type:'increhander',incre:2} dispatch(myAction) } } } export default connect(mapStateToProps,mapDispatchToProps)(ReduxDemo1)
|
redux简化版本
规则放到一个文件中
actionTypes.js代码:
1
| export const increType = 'home/increhander'
|
导出刚才不同actions,不同写法:
actions.js代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
import { increType } from './actionTypes'
export const myActions = (val) => { return { type:increType, incre: val } }
export const myActionsAsync = (val) => { return (dispatch)=>{ setTimeout(() => { dispatch(myActions(5)) }, 2000); } }
|
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import React, { Component } from 'react' import { connect } from 'react-redux' import { myActions, myActionsAsync } from './actions'
@connect( state => ({ mynum: state.num }), dispatch => ({ increfun(val) { dispatch(myActions(val)) }, increfun2() { dispatch(myActionsAsync()) } }) ) class ReduxDemo2 extends Component { render() { return ( <div> <h3>redux使用案例--简化版</h3> <p>{this.props.mynum}</p> <button onClick={() => this.props.increfun(4)}>+3</button> <button onClick={this.props.increfun2}>+5</button> </div> ) } } export default ReduxDemo2
|