React-redux使用

1.actionCreator

// action creator 就是函数而已...
var actionCreator = function() {
    // ...负责构建一个 action (是的,action creator 这个名字已经很明显了)并返回它
    return {
        type: 'AN_ACTION'
    }
}

2.store

import { createStore } from 'redux';
var store = createStore(() => {});//createStore 函数必须接收一个能够修改应用状态的函数

3.reducer

import { createStore } from 'redux';
var store_0 = createStore(() => {});
var reducer = function (...args) {
    console.log('Reducer was called with args', args)
};
var store_1 = createStore(reducer);

4.get-state

import { createStore } from 'redux'
var reducer_0 = function (state, action) {
    console.log('reducer_0 was called with state', state, 'and action', action)
}
var store_0 = createStore(reducer_0)
// 输出: reducer_0 was called with state undefined and action { type: '@@redux/INIT' }
// 为了读取 Redux 保存的 state,你可以调用 getState
console.log('store_0 state after initialization:', store_0.getState())
// 输出: store_0 state after initialization: undefined
/*-----------------------------------------------*/
var reducer_3 = function (state = {}, action) {
    console.log('reducer_3 was called with state', state, 'and action', action)
    switch (action.type) {
        case 'SAY_SOMETHING':
            return {
                ...state,
                message: action.value
            }
        default:
            return state;
    }
}
var store_3 = createStore(reducer_3)
// 输出: reducer_3 was called with state {} and action { type: '@@redux/INIT' }
console.log('store_3 state after initialization:', store_3.getState())
// 输出: store_3 state after initialization: {}

5.combine-reducers

var userReducer = function (state = {}, action) {
    console.log('userReducer was called with state', state, 'and action', action)
    switch (action.type) {
        // etc.
        default:
            return state;
    }
}
var itemsReducer = function (state = [], action) {
    console.log('itemsReducer was called with state', state, 'and action', action)
    switch (action.type) {
        // etc.
        default:
            return state;
    }
}
/*--------------------------------------*/
import { createStore, combineReducers } from 'redux'
var reducer = combineReducers({
    user: userReducer,
    items: itemsReducer
})
var store_0 = createStore(reducer)
// 输出:
// userReducer was called with state {} and action { type: '@@redux/INIT' }
// itemsReducer was called with state [] and action { type: '@@redux/INIT' }

// 正如你从输出中看到的,每个 reducer 都被正确地调用了(但接收了个 init action @@redux/INIT )。
// 这个 action 是什么鬼?这是 combineReducers 实施的一次安全检查,用以确保 reducer 永远不会返回
// undefined。请注意,在 combineReducers 中第一次调用 init action 时,其实是随机 action 来的,
// 但它们有个共同的目的 (即是做一个安全检查)。

console.log('store_0 state after initialization:', store_0.getState())
// 输出:
// store_0 state after initialization: { user: {}, items: [] }

6.dispatch-action(常用的同步action)

var userReducer = function (state = {}, action) {
    console.log('userReducer was called with state', state, 'and action', action)
    switch (action.type) {
        case 'SET_NAME':
            return {
                ...state,
                name: action.name
            }
        default:
            return state;
    }
}
var itemsReducer = function (state = [], action) {
    console.log('itemsReducer was called with state', state, 'and action', action)
    switch (action.type) {
        case 'ADD_ITEM':
            return [
                ...state,
                action.item
            ]
        default:
            return state;
    }
}
import { createStore, combineReducers } from 'redux'
var reducer = combineReducers({
    user: userReducer,
    items: itemsReducer
})
var store_0 = createStore(reducer)
console.log('store_0 state after initialization:', store_0.getState())
// 输出:
// store_0 state after initialization: { user: {}, items: [] }
store_0.dispatch({
    type: 'AN_ACTION'
})
// 输出:
// userReducer was called with state {} and action { type: 'AN_ACTION' }
// itemsReducer was called with state [] and action { type: 'AN_ACTION' }
// 每一个 reducer 都被调用了,但是没有一个 action type 是 reducer 需要的,
// 因此 state 是不会发生变化的:
console.log('store_0 state after action AN_ACTION:', store_0.getState())
// 输出:store_0 state after action AN_ACTION: { user: {}, items: [] }
// 但是,等一下!我们是不是可以用一个 action creator 去发送一个 action?我们确实可以
// 用一个 actionCreator,但由于它只是返回一个 action,那么就意味着它不会携带任何东西
// 到这个例子中。但为了面对未来遇到的困难,我们还是以正确的方式,
// 即以 flux 理论去做吧。让我们使用这个 action creator 发送一个我们想要的 action:
var setNameActionCreator = function (name) {
    return {
        type: 'SET_NAME',
        name: name
    }
}
store_0.dispatch(setNameActionCreator('bob'))
// 输出:
// userReducer was called with state {} and action { type: 'SET_NAME', name: 'bob' }
// itemsReducer was called with state [] and action { type: 'SET_NAME', name: 'bob' }
console.log('store_0 state after action SET_NAME:', store_0.getState())
// 输出:
// store_0 state after action SET_NAME: { user: { name: 'bob' }, items: [] }

7.dispatch-async-action

import { createStore, combineReducers } from 'redux'
var reducer = combineReducers({
    speaker: function (state = {}, action) {
        console.log('speaker was called with state', state, 'and action', action)
        switch (action.type) {
            case 'SAY':
                return {
                    ...state,
                    message: action.message
                }
            default:
                return state;
        }
    }
})
var store_0 = createStore(reducer)
var sayActionCreator = function (message) {
    return {
        type: 'SAY',
        message
    }
}
console.log("\n", 'Running our normal action creator:', "\n")
console.log(new Date());
store_0.dispatch(sayActionCreator('Hi'))
console.log(new Date());
console.log('store_0 state after action SAY:', store_0.getState())
// 输出(忽略初始输出):
//     Sun Aug 02 2015 01:03:05 GMT+0200 (CEST)
//     speaker was called with state {} and action { type: 'SAY', message: 'Hi' }
//     Sun Aug 02 2015 01:03:05 GMT+0200 (CEST)
//     store_0 state after action SAY: { speaker: { message: 'Hi' } }
// ... 结果 store 被立即更新了。
// 我们希望看到的结果应该类似于下面这样的代码:
var asyncSayActionCreator_0 = function (message) {
    setTimeout(function () {
        return {
            type: 'SAY',
            message
        }
    }, 2000)
}
// 但是这样 action creator 返回的不是 action 而是 undefined。所以这并不是我们所期望的解决方法。
// 这里有个诀窍:不返回 action,而是返回 function。这个 function 会在合适的时机 dispatch action。但是如果我们希望
// 这个 function 能够 dispatch action,那么就需要向它传入 dispatch 函数。于是代码类似如下:
var asyncSayActionCreator_1 = function (message) {
    return function (dispatch) {
        setTimeout(function () {
            dispatch({
                type: 'SAY',
                message
            })
        }, 2000)
    }
}
/*===============================================*/
import { createStore, combineReducers } from 'redux'
var reducer = combineReducers({
    speaker: function (state = {}, action) {
        console.log('speaker was called with state', state, 'and action', action)

        switch (action.type) {
            case 'SAY':
                return {
                    ...state,
                    message: action.message
                }
            default:
                return state;
        }
    }
})
var store_0 = createStore(reducer)
var asyncSayActionCreator_1 = function (message) {
    return function (dispatch) {
        setTimeout(function () {
            dispatch({
                type: 'SAY',
                message
            })
        }, 2000)
    }
}
console.log("\n", 'Running our async action creator:', "\n")
store_0.dispatch(asyncSayActionCreator_1('Hi'))
// 输出:
//     ...
//     /Users/classtar/Codes/redux-tutorial/node_modules/redux/node_modules/invariant/invariant.js:51
//         throw error;
//               ^
//     Error: Invariant Violation: Actions must be plain objects. Use custom middleware for async actions.
//     ...

8.middleware(中间件)

// 通常来说中间件是在某个应用中 A 和 B 部分中间的那一块,
// 中间件可以把 A 发送数据到 B 的形式从
// A -----> B
// 变成:
// A ---> middleware 1 ---> middleware 2 ---> middleware 3 --> ... ---> B
// 适合 Redux 处理的内容middleware工作原理:
// action ---> dispatcher ---> middleware 1 ---> middleware 2 ---> reducers
/*-----------------------------------------------*/
// 如上所述,中间件由三个嵌套的函数构成(会依次调用):
// 1) 第一层向其余两层提供分发函数和 getState 函数
//    (因为你的中间件或 action creator 可能需要从 state 中读取数据)
// 2) 第二层提供 next 函数,它允许你显式的将处理过的输入传递给下一个中间件或 Redux
//    (这样 Redux 才能调用所有 reducer)。
// 3) 第三层提供从上一个中间件或从 dispatch 传递来的 action,
//     这个 action 可以调用下一个中间件(让 action 继续流动) 或者
//     以想要的方式处理 action。
// 我们为异步 action creator 提供的中间件叫 thunk middleware
// 它的代码在:https://github.com/gaearon/redux-thunk.
// 它看上去是这样 (为了可读性使用 ES5 语法书写该函数):
var thunkMiddleware = function ({ dispatch, getState }) {
    // console.log('Enter thunkMiddleware');
    return function(next) {
        // console.log('Function "next" provided:', next);
        return function (action) {
            // console.log('Handling action:', action);
            return typeof action === 'function' ?
                action(dispatch, getState) :
                next(action)
        }
    }
}
// 为了让 Redux 知道我们有一个或多个中间件,我们使用 Redux 的
// 辅助函数:applyMiddleware.
// applyMiddleware 接收所有中间件作为参数,返回一个供 Redux createStore 调用的函数。
// 当最后这个函数被调用时,它会产生一个 Store 增强器,用来将所有中间件应用到 Store 的 dispatch 上。
// (来自 https://github.com/rackt/redux/blob/v1.0.0-rc/src/utils/applyMiddleware.js)
// 下面就是如何将一个中间件应用到 Redux store:
import { createStore, combineReducers, applyMiddleware } from 'redux'
const finalCreateStore = applyMiddleware(thunkMiddleware)(createStore)
// 针对多个中间件, 使用:applyMiddleware(middleware1, middleware2, ...)(createStore)
var reducer = combineReducers({
    speaker: function (state = {}, action) {
        console.log('speaker was called with state', state, 'and action', action)

        switch (action.type) {
            case 'SAY':
                return {
                    ...state,
                    message: action.message
                }
            default:
                return state
        }
    }
})
const store_0 = finalCreateStore(reducer)
// 输出:
//     speaker was called with state {} and action { type: '@@redux/INIT' }
//     speaker was called with state {} and action { type: '@@redux/PROBE_UNKNOWN_ACTION_s.b.4.z.a.x.a.j.o.r' }
//     speaker was called with state {} and action { type: '@@redux/INIT' }
// 现在 store 的 middleware 已经准备好了,再来尝试分发我们的异步 action:
var asyncSayActionCreator_1 = function (message) {
    return function (dispatch) {
        setTimeout(function () {
            console.log(new Date(), 'Dispatch action now:')
            dispatch({
                type: 'SAY',
                message
            })
        }, 2000)
    }
}
console.log("\n", new Date(), 'Running our async action creator:', "\n")
store_0.dispatch(asyncSayActionCreator_1('Hi'))
// 输出:
//     Mon Aug 03 2015 00:01:20 GMT+0200 (CEST) Running our async action creator:
//     Mon Aug 03 2015 00:01:22 GMT+0200 (CEST) 'Dispatch action now:'
//     speaker was called with state {} and action { type: 'SAY', message: 'Hi' }
// 当我们调用异步 action creator 两秒之后,action 成功被分发出去。
// 你可能会好奇,一个中间件如何 log 出所有已分发的 action ,
// 是这样:
function logMiddleware ({ dispatch, getState }) {
    return function(next) {
        return function (action) {
            console.log('logMiddleware action received:', action)
            return next(action)
        }
    }
}
// 同样的,下面是一个中间件,它会丢弃所有经过的 action(不是很实用,
// 但是如果加一些判断就能实现丢弃一些 action,放到一些 action 给下一个中间件):
function discardMiddleware ({ dispatch, getState }) {
    return function(next) {
        return function (action) {
            console.log('discardMiddleware action received:', action)
        }
    }
}

9.subscriber(订阅 state 的更新)

import { createStore, combineReducers } from 'redux'
var itemsReducer = function (state = [], action) {
    console.log('itemsReducer was called with state', state, 'and action', action)
    switch (action.type) {
        case 'ADD_ITEM':
            return [
                ...state,
                action.item
            ]
        default:
            return state;
    }
}
var reducer = combineReducers({ items: itemsReducer })
var store_0 = createStore(reducer)
store_0.subscribe(function() {
    console.log('store_0 has been updated. Latest store state:', store_0.getState());
    // 在这里更新你的视图
})
var addItemActionCreator = function (item) {
    return {
        type: 'ADD_ITEM',
        item: item
    }
}
store_0.dispatch(addItemActionCreator({ id: 1234, description: 'anything' }))
// 但是最后我们还是需要一个更好的接口订阅我们的 store变化。这也就是 react-redux 给带给我们的:
// 一个完美填补原生 Redux 订阅机制和开发者的期待之间的空缺的 API ,
// 这样我们不再需要直接使用订阅。而只是
// 使用 “provide” 和 ”connect“ 绑定,不必再关心隐含在内的订阅方法。

10.Provider-and-connect

import React from 'react'
import Home from './home'
import { Provider } from 'react-redux'
export default class Application extends React.Component {
  render () {
    return (
      // As explained above, the Provider must wrap your application's Root component. This way,
      // this component and all of its children (even deeply nested ones) will have access to your
      // Redux store. Of course, to allow Provider to do that, you must give it the store
      // you built previously (via a "store" props).
      <Provider store={ this.props.store }>
        <Home />
      </Provider>
    )
  }
}
最新版的 react-redux 使用方法如下: 首先,确保你的项目已经安装了 react-redux 依赖包。你可以使用以下命令安装它: ``` npm install react-redux ``` 或 ``` yarn add react-redux ``` 接下来,你需要创建一个 Redux store。你可以使用 Redux Toolkit 来简化这个过程。首先,导入 `configureStore` 和 `getDefaultMiddleware` 函数: ``` import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'; ``` 然后,创建一个 rootReducer 来合并你的所有 reducer: ``` import { combineReducers } from 'redux'; const rootReducer = combineReducers({ // 这里是你的 reducer }); ``` 接着,使用 `configureStore` 函数创建 Redux store。你可以通过传入一个对象来配置 store,例如指定 reducer、middleware 等等。以下是一个示例: ``` const store = configureStore({ reducer: rootReducer, middleware: getDefaultMiddleware() }); ``` 现在,你可以使用 `<Provider>` 组件来将 Redux store 提供给你的整个应用程序。在你的根组件中,导入 `<Provider>` 组件和你的 Redux store,然后将其包裹在应用的最外层: ``` import { Provider } from 'react-redux'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); ``` 通过将 Redux store 提供给整个应用程序,你可以在应用的任何地方使用 `useSelector` 和 `useDispatch` 钩子来访问 Redux store 中的状态和分发 action。例如,在你的组件中,你可以这样使用: ``` import { useSelector, useDispatch } from 'react-redux'; const MyComponent = () => { const counter = useSelector(state => state.counter); const dispatch = useDispatch(); // 使用 counter 和 dispatch }; ``` 这就是最新版的 react-redux使用方法。你可以根据你的具体需求,自定义配置和使用其他相关的 react-redux API。希望对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值