Skip to content

Commit 26179a2

Browse files
committed
edit md
1 parent a916c52 commit 26179a2

1 file changed

Lines changed: 98 additions & 1 deletion

File tree

react/redux/README.md

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# Redux
2-
前端框架的组件式开发永远有一道鸿沟——跨组件通信。我在 [Vue 教程](https://github.com/wscats/vue/tree/master/VueBasic/Vuex)中有提到过,如果对跨组件通信不明白的可先跳过去看看。
32

43
React 不同与双向数据绑定框架,它是单向数据流,所以每次更新都得调用`setState`,所以在跨组件通信中会比较迂回。还有就是 React 没有逻辑分层,在开发过程中,逻辑分层是很重要的。
54

@@ -83,3 +82,101 @@ export default class Component1 extends Component{
8382
- View 层
8483
- 视图层,也就是组件
8584
- 通过`getState()`获取的值然后再`setState`便可以显示。
85+
86+
# 基础入门
87+
88+
一般用于复杂的组件之间通信数据,比如
89+
90+
- 父传子(props)
91+
- 兄弟通信(redux/vuex)平行组件之间的通信
92+
93+
```js
94+
State(存放数据的地方)通信的数据都会存放在这里
95+
Getter (获取需要通信的数据)
96+
Mutation (修改交换的数据)
97+
Action (触发Mutation)
98+
Module (分开多个State仓库)
99+
```
100+
101+
## 安装
102+
103+
安装`redux`的两个必须模块
104+
```js
105+
cnpm install --save redux
106+
npm install --save react-redux
107+
```
108+
109+
## 创建仓库
110+
111+
创建一个仓库,最终目的就是要生成一个`store`仓库,该仓库有一个`state`存放数据
112+
还有一个`action`来触发`state`的更改
113+
```js
114+
import { createStore } from 'redux'
115+
// react的写法
116+
const store = createStore((state = 0, action) => {
117+
switch (action.type) {
118+
case 'INCREMENT':
119+
return state + 1
120+
case 'DECREMENT':
121+
return state - 1
122+
default:
123+
return state
124+
}
125+
})
126+
// vue的写法
127+
const store = new Vuex.Store({
128+
state: {
129+
count: 0
130+
},
131+
mutations: {
132+
increment(state) {
133+
state.count++
134+
}
135+
}
136+
})
137+
```
138+
139+
## 与react进行关联
140+
141+
`<Provider>`注入到根组件里面,把`<Router>``<App />`组件包含起来,把刚才上面生成的`store`注入到`<Provider store={store}>`组件里面,这个时候,整个app的都可以`redux`的状态管理
142+
```js
143+
// 把上面配置好的store和react进行关联
144+
import { Provider, connect } from 'react-redux';
145+
ReactDOM.render(
146+
<Provider store={store}>
147+
<Router>
148+
<App />
149+
</Router>
150+
</Provider>
151+
, document.getElementById('root'));
152+
```
153+
154+
## connect
155+
156+
把组件和`store`进行一次关联。就如果没有`connect`,这个仓库是没有任何人能访问的
157+
```js
158+
import { connect } from 'react-redux';
159+
// 该组件如果想跟store进行连接就在导出的时候用
160+
export default connect((state) => {
161+
// 第一个函数把store里面的值注入到Wnav组件的`props`上面
162+
// 第一个函数是获取store的值
163+
164+
// 和store的state产生关系
165+
console.log(state)
166+
return state
167+
}, (dispatch) => {
168+
// 第二个函数是触发store的值改变
169+
// 相当于vue(action,commit->mutation)
170+
// 你可以在此处定义多个函数,来去触发store里面的`dispatch`,从而改变`store`里面的值
171+
172+
// 和store的action产生关系
173+
return {
174+
onIncreaseClick() {
175+
dispatch("increaseAction")
176+
}
177+
}
178+
})(Wnav);
179+
180+
// 不连接store的话
181+
// export default Wnav
182+
```

0 commit comments

Comments
 (0)