Redux学习

这篇博客介绍了Redux的工作流程,包括如何创建仓库、管理状态。作者详细展示了在React中如何使用Redux,从创建store、reducer到组件中订阅store状态变化。此外,还讲解了如何在组件挂载后利用Axios获取数据,并将数据通过Action传递到Redux。最后,讨论了Redux-thunk中间件的应用,特别是在处理异步操作中的作用。
摘要由CSDN通过智能技术生成

title: Redux学习
date: 2021-08-24 11:14:16
tags: react
description: Redux学习

1. Redux工作流程

img

2.创建Redux中的仓库

// npm install --save redux

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

const store = createStore(reducer) // 创建数据存储仓库

export default store
// store/reducer.js
cosnt defaultState = {
    inputValue: 'Write Something',
    list: [
        'xxx',
        'xxxx'
    ]
}
export default (state = defaultState, action) => { // state指原始仓库里的状态,action指action新传递的状态
	if(action.type === 'changeInput'){
        let newState = JSON.parse(JSON.stringify(state)) // 深度拷贝state
        newState.inputValue = action.value
        return newState
    }
    return state
}
// src/TodoList.js
import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Input , Button , List } from 'antd'
import store from './store'

class TodoList extends Component {
constructor(props){
    super(props)
    //关键代码-----------start
    this.state=store.getState();
    //关键代码-----------end
    this.changeInputValue = this.changeInputValue.bind(this) // 修改this的指向
    this.storeChange = this.storeChange.bind(this)
    store.subscribe(this.storeChange) // 订阅Redux的状态
}
changeInputValue(e) {
    // console.log(e.target.value)
    // 改变Redux中的state的值要通过Action
    const action = {
        type: 'change_input_value', // 对action的描述
        value: e.target.value // 要改变的值
    }
    store.dispatch(action) // 通过dispatch()方法把action传递给store
}
storeChange(){
    this.setState(store.getState) // store中状态改变时更新state
}
    render() { 
        return ( 
            <div style={{margin:'10px'}}>
                <div>
                    <Input 
                        placeholder={this.state.inputValue} 
                        style={{ width:'250px', marginRight:'10px'}}
                        onChange={this.changeInputValue}
                     />
                    <Button type="primary">增加</Button>
                </div>
                <div style={{margin:'10px',width:'300px'}}>
                    <List
                        bordered
                        //关键代码-----------start
                        dataSource={this.state.list}
                        //关键代码-----------end
                        renderItem={item=>(<List.Item>{item}</List.Item>)}
                    />    
                </div>
            </div>
         );
    }
}
export default TodoList;

3. Axios与Redux结合

在componentDidMount()中通过axios获取数据

export const getListAction = (data) => ({
    type: GET_LIST,
    data
})

componentDidMount() {
	axios.get('xxxx'.then(res=>{
        const data = res.data
        const action = getListAction(data)
        store.dispatch(action)
    }))
}

4. Redux-thunk中间件

应用场景:Dispatch一个Action之后,到达reducer之前,进行一些额外的操作

在实际工作中你可以使用中间件来进行日志记录、创建崩溃报告,调用异步接口或者路由

// npm install --save redux-thunk
import { createStore , applyMiddleware } from 'redux' 
import thunk from 'redux-thunk'
const store = createStore(
    reducer,
    applyMiddleware(thunk)
) // 创建数据存储仓库
export default store   //暴露出去
// actionCreators.js

import axios from 'axios'
...something...
export const getTodoList = () =>{
    return (dispatch)=>{
        axios.get('https://www.easy-mock.com/mock/5cfcce489dc7c36bd6da2c99/xiaojiejie/getList').then((res)=>{
            const data = res.data
            const action = getListAction(data)
            dispatch(action)
            // console.log(data)
        })
    }
}
// TodoList.js

//先引入getTodoList
import {getTodoList , changeInputAction , addItemAction ,deleteItemAction,getListAction} from './store/actionCreatores'
---something---
componentDidMount(){
    const action = getTodoList()
    store.dispatch(action)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值