随笔
-
connect 把 redux 中的属性和方法映射到对应的组件中
import { connect } from "react-redux";
-
通过 dispatch 派发一个 action 来改变 state
props.dispatch(countAdd(2));
-
connect 是一个高阶函数,所谓的高阶函数(纯函数):就是接收一个 function 作为参数,经过包装之后生成一个新的 function。
connect 有两个参数:
- connect 的第一个参数是一个 function,表示当前组件中可以使用的 state 数据。
- 可以把 redux 中的 state 数据映射到组件的 props 对象上
export default connect(function(state) {
return state;
})(App);
Redux
Redux 提供 createStore 这个函数,用来生成 Store。
createStore 函数接受另一个函数作为参数,返回新生成的 Store 对象。
import { createStore } from "redux";
const store = createStore(fn);
const state = store.getState();
Action
const action = {
type: 'ADD_TODO',
payload: 'Learn Redux'
};
Action 是一个对象。其中的type属性是必须的,表示 Action 的名称。
Action Creator 定义一个函数来生成 Action
const ADD_TODO = ‘添加 TODO’;
```js
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
const action = addTodo('Learn Redux');
store.dispatch() 是 View 发出 Action 的唯一方法。
```
Reducer
Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。