Redux

DOC

https://reacttraining.com/react-router/web/api
https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux

概述

Redux参考了Flux的思路,所有的状态都包含在store.state中,外部不能对它进行修改,只能通过store.dispatch来发起一个action来修改。那store怎么来呢?Redux提供了一个函数:createStore来创建,它接受一个reducer作为参数。reducer就是一个接口定义,需要我们自己去实现:reducer(previousState, action) => newState.即,根据previousStateaction生成一个新的newState。这样就串起来了,dispatch(action)reducernewState

middleware

实现热插拔的插件,它不会涉及reducer的改变。即利用store和reducer去执行多种串行或不相干的过程。

react-router-dom

BrowserRouter

<BrowserRouter>使用H5的==history== API(pushState, replaceState and the popstate event) 来维持UI与URL的同步。

1
2
3
4
5
6
7
8
9
10
import { BrowserRouter } from 'react-router-dom'

<BrowserRouter
basename={optionalString}
forceRefresh={optionalBool}
getUserConfirmation={optionalFunc}
keyLength={optionalNumber}
>
<App/>
</BrowserRouter>

react-router-redux

用途

主要是将应用的路由信息与Redux中的store绑定在一起。
所有的应用状态必须放在一个单一的store中管理,路由状态也不例外。

安装

1
2
npm install --save react-router-redux@next
npm install --save history

基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import React from 'react'
import ReactDOM from 'react-dom'

import { createStore, combineReducers, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'

import createHistory from 'history/createBrowserHistory'
import { Route } from 'react-router'

import { ConnectedRouter, routerReducer, routerMiddleware, push } from 'react-router-redux'

import reducers from './reducers' // Or wherever you keep your reducers

// Create a history of your choosing (we're using a browser history in this case)
const history = createHistory()

// Build the middleware for intercepting and dispatching navigation actions
const middleware = routerMiddleware(history)

// Add the reducer to your store on the `router` key
// Also apply our middleware for navigating
const store = createStore(
combineReducers({
...reducers,
router: routerReducer
}),
applyMiddleware(middleware)
)

// Now you can dispatch navigation actions from anywhere!
// store.dispatch(push('/foo'))

ReactDOM.render(
<Provider store={store}>
{ /* ConnectedRouter will use the store from Provider automatically */ }
<ConnectedRouter history={history}>
<div>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
)

这样利用store.dispatch(push('/home''));来分发一个路由变动的action

https://segmentfault.com/a/1190000009621052

  • 将React Router与Redux store绑定。

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. DOC
  2. 2. 概述
  3. 3. middleware
  4. 4. react-router-dom
    1. 4.1. BrowserRouter
  5. 5. react-router-redux
    1. 5.1. 用途
    2. 5.2. 安装
    3. 5.3. 基本使用
,