redux入门级使用

redux使用

demo的git地址

1.简单使用redux

redux流程

redux流程
举个例子理解,假设我们想要得到的state为图书。我们告诉图书管理员想要的书籍,图书管理员在图书馆会通过图书管理软件来寻找具体位置,然后找到再给我们
图书馆借书模拟redux流程

安装redux

yarn add redux

创建store文件夹

store文件夹目录
actionCreators:图书管理员,定义action,通过stroe.dispatch(action)
index.js:相当于图书馆
reducer.js:图书管理软件,处理state的地方,抛出newState给store
actionTypes:防止因type写错造成的不报错的bug

store/index.js
import { createStore } from 'redux'
import reducer from './reducer'

//createStore只接受两个参数
const store = createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    //如果window有REDUX_DEVTOOLS_EXTENSION程序,则执行程序方法,&&表示如果符合,可以看到store中state的变化过程,要在chrome商店中安装redux DevTools
)
export default store

store/actionTypes.js
export const CHANGE_INPUT = 'changeInput'
store/actionCreators.js
//图书管理员
import { CHANGE_INPUT } from './actionTypes'
//返回对象({})
export const changeInputAction = (value)=>({
    type:CHANGE_INPUT,//type有点标识符的意思
    value
})
store/reducer.js
import {CHANGE_INPUT} from './actionTypes'
//暴露出去方法
//默认值
const defaultState = {
    inputValue:'Writing Someting'
}
//reducer必须是纯函数。最后返回的return值只根据传进来的(state,action)参数改变
export default(state=defaultState,action)=>{
    console.log("state",state)
    console.log("action",action)//type:changeInput,value:'变化'
    //注意reducer中只能接收state,不能改变state
    if(action.type === CHANGE_INPUT){
        //为了return改变了的值,深拷贝state
        let newState = JSON.parse(JSON.stringify(state))
        newState.inputValue = action.value
        return newState
    }
    return state
}

components/TodoList.js
import React, { Component,Fragment } from 'react';
import { Input } from 'antd';
import store from './store'
import { changeInputAction } from './store/actionCreators'
//无状态组件应该用方法,性能更加
class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = store.getState()
        this.changeInputValue = this.changeInputValue.bind(this)
    }

    render() { 
        return (  
            <Fragment>
                <div style={{marginTop:'20px'}}>
                    <Input 
                        style={{width:'300px',marginRight:'10px'}} 
                        onChange={this.changeInputValue}
                    />
                </div>
            </Fragment>
        );
    }
    changeInputValue(e){
        //建立action
        const action = changeInputAction(e.target.value)
        //把action用displatch推送到store,由于store图书馆没有操作能力,会被推送给reducer
        store.dispatch(action)
    }
}
 
export default TodoList;

2.redux中间件(常用在异步,日志等)

2.1redux-thunk
安装redux-thunk

yarn add redux-thunk

store/index.js配置
//applyMiddleware中间件,compose做增强函数
import {createStore,applyMiddleware, compose} from 'redux'
import reducer from './reducer'
//引入reduxthunk
import thunk from 'redux-thunk'
//store是唯一的
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const enhancer = composeEnhancers(applyMiddleware(thunk))
//createStore只接受两个参数
const store = createStore(
    reducer,
    enhancer
)
export default store
store/actionCreators.js
import { GET_LIST } from './actionTypes'
import { getTodo }from '../api/todo'

export const getListAction = (data)=>({
    type:GET_LIST,
    data
})
//返回函数
export const getTodoList = ()=>{
    return (dispatch)=>{
        getTodo().then((res)=>{//异步请求
        	//去触发reducer
            const action = getListAction(res.data.data)
            dispatch(action)
            console.log("res",res.data.data)
        })
    }
}
store/reducer.js
import {GET_LIST} from './actionTypes'
//默认值
const defaultState = {
    list:[]
}
//reducer必须是纯函数。最后返回的return值只根据传进来的(state,action)参数改变
export default(state=defaultState,action)=>{
    if(action.type === GET_LIST){
        //为了return改变了的值,深拷贝state
        let newState = JSON.parse(JSON.stringify(state))
        newState.list = action.data
        return newState
    }
    return state
}
components/TodoList.js
import React, { Component,Fragment } from 'react';
import { List } from 'antd';
import store from './store'
import { getTodoList } from './store/actionCreators'
//无状态组件应该用方法,性能更加
class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = store.getState()
    }
    //请求列表list,改变store中state.list的值
    componentDidMount(){
        const action = getTodoList()
        store.dispatch(action)
    }
    render() { 
        return (  
            <Fragment>
                <div style={{marginTop:'20px'}}>
                    <List
                        size="large"
                        bordered
                        dataSource={this.state.list}
                        renderItem={(item) => 
                            <List.Item>{item}</List.Item>} 
                        />
                </div>
            </Fragment>
        );
    }
}
 
export default TodoList;
2.2redux-saga

saga相比thunk的使用上要麻烦一点

安装redux-saga

yarn add redux-saga

创建store/sagas.js

redux-saga在sagas.js中写中间步骤

import {takeEvery, put} from 'redux-saga/effects'
import {GET_SAGA_LIST} from './actionTypes'
import { getTodo } from '../api/todo'

import  { getListAction } from './actionCreators'
//generator 函数。异步,es6语法
function* mySaga(){
    yield takeEvery(GET_SAGA_LIST,getList)//等待监听,因为在前面的todoList组件中做了getTodoList的action,所以能捕获,捕获到后做getList
}

function* getList(){
    console.log("捕获到了")
    const res = yield getTodo()
    const action = getListAction(res.data.data)//调用getListAction,type:GET_LIST
    yield put(action)//这里不用dispatch而是put,进reducer.JS
}
export default mySaga
配置store/index,js
//applyMiddleware中间件,compose做增强函数
import {createStore,applyMiddleware, compose} from 'redux'
import reducer from './reducer'
//引入reduxsaga
import createSagaMiddleware from 'redux-saga'
import mySagas from'./sagas'
//创造saga中间件
const sagaMiddleware = createSagaMiddleware()
//store是唯一的
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware))
//createStore只接受两个参数
const store = createStore(
    reducer,
    enhancer
)
//跑一下mySagas
sagaMiddleware.run(mySagas)
export default store
store/actionCreators.js
import { GET_LIST,GET_SAGA_LIST } from './actionTypes'
//返回对象({})
export const getListAction = (data)=>({
    type:GET_LIST,
    data
})
//返回函数
export const getTodoList = ()=>({
    type:GET_SAGA_LIST
})
store/reducer.js
import {GET_LIST} from './actionTypes'
//默认值
const defaultState = {
    list:[]
}
//reducer必须是纯函数。最后返回的return值只根据传进来的(state,action)参数改变
export default(state=defaultState,action)=>{
    if(action.type === GET_LIST){
        //为了return改变了的值,深拷贝state
        let newState = JSON.parse(JSON.stringify(state))
        newState.list = action.data
        return newState
    }
    return state
}
components/TodoList.js
import React, { Component,Fragment } from 'react';
import { List } from 'antd';
import store from './store'
import { getTodoList } from './store/actionCreators'
//无状态组件应该用方法,性能更加
class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = store.getState()
    }
    //请求列表list,改变store中state.list的值
    componentDidMount(){
        const action = getTodoList()
        store.dispatch(action)
    }
    render() { 
        return (  
            <Fragment>
                <div style={{marginTop:'20px'}}>
                    <List
                        size="large"
                        bordered
                        dataSource={this.state.list}
                        renderItem={(item) => 
                            <List.Item>{item}</List.Item>} 
                        />
                </div>
            </Fragment>
        );
    }
}
 
export default TodoList;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值