redux
强调的是,redux 与 react 并没有直接关系,它是一个独立的 JavaScript 状态管理库(数据),如果我们希望中 React 中使用 Redux,需要先安装 react-redux
安装
npm i -S redux react-redux
Provider 组件
想在 React 中使用 Redux ,还需要通过 react-redux 提供的 Provider 容器组件把 store 注入到应用中
Provider把 store 当做一个组件刷新
![](https://img.haomeiwen.com/i12421083/6e3b02d71a352b46.png)
connect 方法
有了 connect 方法,我们不需要通过 props 一层层的进行传递, 类似路由中的 withRouter ,我们只需要在用到 store 的组件中,
通过 react-redux 提供的 connect 方法,把 store 注入到组件的 props 中就可以使用了
![](https://img.haomeiwen.com/i12421083/240d70da401fba28.png)
默认情况下,connect 会自动注入 dispatch 方法
注入 state 到 props
![](https://img.haomeiwen.com/i12421083/7c2a4ce2b8c264a4.png)
connect 方法的第一个参数是一个函数
- 该函数的第一个参数就是 store 中的 state : `store.getState()`
- 该函数的返回值将被解构赋值给 props : `this.props.items`
![](https://img.haomeiwen.com/i12421083/1ffcf6fa86a79aac.png)
Redux DevTools extension
为了能够更加方便的对 redux 数据进行观测和管理,我们可以使用 Redux DevTools extension 这个浏览器扩展插件
https://github.com/zalmoxisus/redux-devtools-extension
![](https://img.haomeiwen.com/i12421083/55c04be9fba9f165.png)
打开浏览器开发者工具面板 -> redux
异步 action
许多时候,我们的数据是需要和后端进行通信的,而且中开发模式下,很容易就会出现跨域请求的问题,好在 create-react-app
中内置了一个基于 node 的后端代理服务,我们只需要少量的配置就可以实现跨域
package.json 配置
相对比较的简单的后端 URL 接口,我们可以直接中 package.json 文件中进行配置
后端接口
http://localhost:7777/api/items
![](https://img.haomeiwen.com/i12421083/154faa9faa9eb8d6.png)
./src/setupProxy.js 配置
针对相对复杂的情况,可以有更多的配置
npm i -S http-proxy-middleware
![](https://img.haomeiwen.com/i12421083/7de45baf2cb33f5e.png)
其它代码同上
Middleware
默认情况下,dispatch 是同步的,我们需要用到一些中间件来处理
![](https://img.haomeiwen.com/i12421083/3ef31a1a093bbe6f.png)
const logger = store => next => action => {
console.group(action.type)
console.info('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
console.groupEnd(action.type)
return result
redux.applyMiddleware
通过 applyMiddleware 方法,我们可以给 store 注册多个中间件
注意:devTools 的使用需要修改一下配置
npm i -D redux-devtools-extension
![](https://img.haomeiwen.com/i12421083/7f15eb5f9cbde403.png)
redux-thunk
这是一个把同步 dispatch 变成异步 dispatch 的中间件
安装
npm i -S redux-thunk
![](https://img.haomeiwen.com/i12421083/e7f4e88eae299ad0.png)
import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import user from './reducer/user';
import items from './reducer/items';
import cart from './reducer/cart';
let reducers = combineReducers({
user,
items,
cart
});
const store = createStore(
reducers,
composeWithDevTools(applyMiddleware(
thunk
))
);
网友评论