关于redux:redux总结

Redux 是什么

Redux is a predictable state container for JavaScript apps

Redux概念

store: 利用数据的存储核心
action: 利用数据的扭转的形容
reducer: 决定利用数据新状态的函数,接管利用之前的状态和一个 action 返回数据的新状态。
state: 状态
middleware: redux 提供中间件的形式,实现一些 流程的自定义管制,同时造成其插件体系。

流程

环境筹备

npx create-react-app cra
cd cra 
npm start

在 cra我的项目中装置redux

yarn add redux

redux整体感知

// reducer
const weight = (state = 160, action) => {
    switch (action.type) {
        case 'eat':
            return state + 10
        case 'hungry':
            return state - 10
        default:
            return 160
    }
}

const store = createStore(weight)

console.log(store.getState())

store.dispatch({ type: 'eat' })
console.log('我吃了一些事物')
console.log(store.getState())

console.log('我饿了好几天')
store.dispatch({ type: 'hungry' })
console.log(store.getState())
console.log('我又饿了好几天')
store.dispatch({ type: 'hungry' })
console.log(store.getState())

reducer 外面应用switch语句依据传入的类型,输入新的状态
把reducer 传入 createStore(weight)
通过 dispatch 传入不同的类型,扭转状态state。
store.dispatch({ type: ‘hungry’ })
通过 store.getState() 获取以后的状态

通过subscribe订阅,实现redux数据响应

const store = createStore(weight)


const watch = () => {
    const cur = store.getState()
    console.log(`stark wang 当初体重为${cur}斤`)
}

store.subscribe(watch)
// watch()


store.dispatch({type:'eat'})

store.dispatch({type:'eat'})

store.dispatch({type:'eat'})

store.dispatch({ type: 'hungry' })

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理