1. 什么是 redux?
Redux is a predictable state container for JavaScript apps.
It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.
You can use Redux together with React, or with any other view library. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available. .
- Redux 是一个可用于 JS apps 的 可预见的状态容器。
- 它很小,只有 2KB.
- 因为只是一个状态容器,可以与 任意 view library 一起用,如 Reactjs, Vuejs.
2. 流程图解释
解释:
- UI 指的是 React,视图层(view), 展示数据
- 当用户在 UI 点击了, 事件就会触发
- Event Handler 中, store 就会派发事件(
store.dispatchj(action) ) - action 由 actionCreator 创建,必须返回带有 type 属性的对象
{ type: 'Add' } - reducer 根据 action type,进行相对应的操作
- reducer 必须是一个纯函数,任何时候传入同样的参数,都能得到同样的结果 - 纯函数有利于 redux 底层进行程序优化
3. show you code!!!
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="node_modules/redux/dist/redux.min.js"></script>
</head>
<body>
<h1>当前的数量:<span class="value">0</span></h1>
<button class="add">+1</button>
<button class="minus">-1</button>
<script>
// action creator
const Add = () => {
return {
type: 'Add'
}
}
const Minus = () => {
return {
type: 'Minus'
}
}
// reducer
const reducer = (state = 100, action) => {
switch (action.type) {
case 'Add':
return state + 1;
case "Minus":
return state - 1
}
return state
}
const {createStore} = window.Redux
// 传入 reducer
const store = createStore(reducer)
document.querySelector('.value').innerHTML = store.getState()
// 1. subscribe: 只要 state tree 改变, listener 就会执行
const unsubscribe = store.subscribe(() => {
console.log(store.getState())
document.querySelector('.value').innerHTML = store.getState()
})
// store.dispatch(Add())
// store.dispatch(Add())
// 2. action: 增
document.querySelector('.add').onclick = () => {
store.dispatch(Add())
}
// 3. action: 减
document.querySelector('.minus').onclick = () => {
store.dispatch(Minus())
}
// 4. 取消 subscribe, 5秒之后
setTimeout(() => {
unsubscribe()
}, 5000)
</script>
</body>
</html>
|