React的状态管理库redux的使用

redux是JavaScript应用的状态容器,提供可预测花的状态管理。它保证程序行为一致性且易于测试。

1.安装redux

npm install redux -S

2.使用步骤

(1)需要一个store来存储数据
(2)store里的reducer初始化state并定义state修改规则
(3)通过dispatch一个action来提交对数据的修改
(4)action提交到reducer函数里,根据传入的action的type,返回新的state 

3.代码示范

(1)创建store,src/store/index.js
import {createStore} from 'redux'
// reducer是纯函数
const counterReducer = (state=0,action)=>{
    switch(action.type){
        case 'ADD':
            return state+1
        case 'MINUX':
            return state-1
        default: 
            return state
    }
} 
const store = createStore(counterReducer)
export default store
(2)在page页面使用,reduxpage.js
import React,{Component} from 'react'
import store from '../store/index.js'
export default class ReduxPage extends Component {
    componentDidMount(){
        //第一种更新办法
        store.subscribe(()=>{
            this.forceUpdate()//强制刷新
        })
    }
    render(){
        return (
            <div>
                <p>{store.getState()}</p>
                <button onClick={()=>store.dispatch({type:'ADD'})}>增加</button>
            </div>
        )
    }
}
//第二种更新办法
在index.js中
import store from './store'
ReactDOM.render(<App/>,document.getElementById('root'))
store.subscribe(()=>{
    ReactDOM.render(<App/>,document.getElementById('root'))
}) 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值