redux使用及理解

2020-06-21  本文已影响0人  Poppy11
Redux的特点

统一的状态管理,一个应用中只有一个仓库(store)
仓库中管理了一个状态树(statetree)
仓库不能直接修改,修改只能通过派发器(dispatch)派发一个动作(action)
更新state的逻辑封装到reducer中

Redux能做什么?

随着JavaScript单页应用开发日趋复杂,管理不断变化的state非常困难,Redux的出现就是为了解决state里的数据问题。在React中,数据在组件中是单向流动的,数据从一个方向父组件流向子组件(通过props),由于这个特征,两个非父子关系的组件(或者称作兄弟组件)之间的通信就比较麻烦

redux中各对象的说明
{type: UPDATE_TITLE_COLOR, payload: 'green'}

步骤

1、首先创建redux文件夹,文件夹包含action,reducer和store.js


image.png

2、store.js里面创建仓库,还有就是因为后期需要调试redux,去谷歌商店下载redux-devtools这个插件,并且在store.js里面进行配置,代码如下

import {createStore, applyMiddleware,compose} from 'redux'
import thunkMiddleware from 'redux-thunk'
import reducer from '../redux/reducer'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(applyMiddleware(thunkMiddleware)))

export default store

3、将store引入给 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux'
import store from './redux/store'

ReactDOM.render(
    <Provider store={store}>
        <App />,
    </Provider>,
  document.getElementById('root')
);


3、首先使用dispatch触发action

 dispatch({
          type: 'INIT_USER',
          user: res.body
        })

4、因为只有reducer能改变状态,所以会根据接受的action.type来给state赋值

const init = {
  id: -1,
  name: 'admin',
  roles:[]
}


//编写reducer,实现更新state的具体逻辑
export default (state = init, action) => {
  switch (action.type) {
    case 'INIT_USER':
      return action.user
    default:
      return state
  }
}

5、然后将所有reducer引入index文件,并且创建容器,传入reducer

export default combineReducers({
  user,
})

上一篇 下一篇

猜你喜欢

热点阅读