redux 的基础使用

  1. 安装 redux
# NPM
npm install redux

# Yarn
yarn add redux
  1. 创建redux文件
// actionTypes.js    公共变量,避免多次使用时书写错误
	export const INCREMENT = 'increment'
	
// actions.js   //为描述应用程序中发生了什么的事件.
// 同步方法
	export const increment = count => ({ type: INCREMENT, data: count })
	
// reducers  // 事件监听器,它根据接收到的 action(事件)类型处理事件。
import { combineReducers } from 'redux'// 多个方法时 用combineReducers暴露且 combineReducers 是对象
import { INCREMENT} from './actionsTypes'
const countAdd = (state = 0, action) => {
  switch (action.type) {
    case INCREMENT:
      return state + action.data
    default:
      return state
  }
}
const xxx = (state, action) => {}
export default combineReducers({countAdd, xxx})

// store //当前 Redux 应用的状态存在于一个名为 store 的对象中  通过 getstate 取值
import { createStore } from 'redux'

import reducers from './reducers'

// 生成一个store对象
const store = createStore(reducers) // 内部会第一次调用reduer函数得到初始state

export default store

注意

store 需要在 根目录引入  
// index.js
import store from './redux/store'
ReactDOM.render(
  <React.StrictMode>
    <App  store= {store} />
  </React.StrictMode>,
  document.getElementById('root')
);

// 需要用 subscribe 监听 store的变化
store.subscribe(()=>{
ReactDOM.render(
  <React.StrictMode>
    <App  store= {store} />
  </React.StrictMode>,
  document.getElementById('root')
);
})

// 改写
function render() {
  ReactDOM.render(<App store={store}/>, document.getElementById('root'))
}
// 初始化渲染
render()
// 订阅监听(store中的状态变化了, 就会自动调用进行重绘)
store.subscribe(render)
  1. 使用
// 在使用的文件 引入actions里面的方法
// 例如
import {increment} from './redux/actions'
export default class App extends Component {

  increment = () => {
    // 1. 得到选择增加数量
    const number = this.select.value * 1
    // increment调用方法传值 
    this.props.store.dispatch(increment(number))
  }

  render() {
  // 通过 this.props.countAdd.getState 取state变化后的值  // countAdd是 reducers 里面暴露的方法
    const {countAdd} = this.props.store.getState()
    console.log(this.props.store.getState().countAdd)
    return (
     <button onClick={this.increment}>+</button>
     )
  }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值