深度理解redux(二)

1、前一篇说了redux的一些基本概念和用法,这一篇我们研究在react中如何使用redux,在react中使用redux的一些不同点。

2、redux中,我们通过store.subscribe()进行数据监听,来更新页面。在react中,我们针对了redux进行了react版本的一些增强(基本不使用store.subscribe()函数),具体就是”react-redux”,所以我们在react的使用中一般都会引入这两个库,”redux”和”react-redux”;

3、引入语法是:

import { createStore, combineReducers } from "redux";
import { Provider, connect } from "react-redux";
   
   
  • 1
  • 2

一般而言,使用的就是这四个。。。。东西。
4、createStore是用来创建数据容器的。基本语法是这样的:

const store = createStore(reducer);
   
   
  • 1

5、combineReducers顾名思义,就是合并reducer,一般而言,一个应用的数据是很多的,用户的行为也是多种多样的,所以reducer函数也就有很多,combineReducers的作用就是合并这些reducer函数的。
基本语法如下:

import { combineReducers } from "redux";
function reducer1(state = 0, action){
    switch (action.type){
        case "ADD":
            return state+1;
        default:
            return state;
    }
}
function reducer2(state=[], action){
    switch (action.type){
        case "ADD_TODO":
            return [...state, action.text];
        default:
            return state;
    }
}
const todoApp = combineReducers({
    reducer1,
    reducer2,
});
export default todoApp;
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

6、Provider是一个组件,用来注入store,一般放在一个项目的最外层。基本语法:

import { Provider } from "react-redux";
render(<Provider store={store}>
<Main />
</Provider>,document.getElementById("root"));
   
   
  • 1
  • 2
  • 3
  • 4

7、connect顾名思义,连接,就是那里需要进行数据处理,我把这个组件连接到store,就直接可以取用store中的state以及dispatch方法。
其中,state就是获取数据的对象,dispatch就是用于发出用户action的。
基本使用示例:

import { connect } from 'react-redux';
import ContentComponent from '../components/ContentComponent';
let mapStateToProps = (state)=> {
    console.log(state);
    return {
        array:filterArray(state.todos,state.visibilityFilter),
        state,
    }
}
export default connect(mapStateToProps)(ContentComponent);
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

8、实践
我自己提供的一个todos示例,代码太长,给出github地址:
[email protected]:liwudi/redux_todos.git
启动方式:
在根目录下,npm install
然后npm start启动项目。

在看这个示例之前,建议先学习一个简单的计数器的示例demo,官方网站中有这样的示例:
参考地址:http://cn.redux.js.org/docs/introduction/Examples.html

猜你喜欢

转载自blog.csdn.net/qq_36486737/article/details/82453988