react-redux使用(发送请求时)

在这里插入图片描述

npm install redux react-redux --save
npm install axios --save

index.js

import React from 'react'
import ReactDom from 'react-dom'


import { Provider } from 'react-redux'


import App from './App'
import store from './store'


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


App.js



import React, { PureComponent } from 'react'
import { BlogList } from './components/index'

export default class App extends PureComponent {

    render() {
        return (
            <div>
                <BlogList />
            </div>
        )
    }
}

store.js

import { createStore, applyMiddleware } from 'redux'

import thunk from 'redux-thunk'

import rootreducer from './reducers'

export default createStore(rootreducer, applyMiddleware(thunk))

actions/blog.js

import actionTypes from './actionType'
// 引入数据请求方法,下面要请求数据
import { getPosts } from '../services/index'


const startFetchBlogList = () => {
    return {
        type: actionTypes.START_FETCH_BLOG_LIST
    }
}

// 请求成功需要传数据payload形参,传递出去reducer才能取到
const fetchBlogSuccess = (payload) => {
    return {
        type: actionTypes.FETCH_BLOG_LIST_SUCCESS,
        payload
    }
}

const fetchBlogFailed = () => {
    return {
        type: actionTypes.FETCH_BLOG_LIST_FAILED
    }
}

export const fetchBlogList = () => dispatch => {
    dispatch(startFetchBlogList())
    getPosts()
        .then((res) => {
            console.log(res)
            if (res.status === 200) {
            // 请求成功需要把数据传过去
                dispatch(fetchBlogSuccess({
                    list: res.data
                }))
            } else {
                dispatch(fetchBlogFailed())
            }
        })
        .catch((err) => {
            console.log(err)
            dispatch(fetchBlogFailed())
        })
}

actions/actionType.js

export default {
    START_FETCH_BLOG_LIST: 'START_FETCH_BLOG_LIST',
    FETCH_BLOG_LIST_SUCCESS: 'FETCH_BLOG_LIST_SUCCESS',
    FETCH_BLOG_LIST_FAILED: 'FETCH_BLOG_LIST_FAILED'
}

services/index.js

import axios from 'axios'


const ajax = axios.create({
    baseURL: 'http://jsonplaceholder.typicode.com'
})

export const getPosts = () => {
    return ajax.get('/posts')
}

reducers/blog.js



import actionTypes from '../actions/actionType'
const initState = {
    list: [{
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
        "userId": 1,
        "id": 2,
        "title": "qui est esse",
        "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
    }],
    isLoading: false,
    errMsg: ''
}

export default (state = initState, action) => {
    switch (action.type) {
        case actionTypes.START_FETCH_BLOG_LIST:
            return {
                ...state,
                isLoading: true
            }
        case actionTypes.FETCH_BLOG_LIST_SUCCESS:
            return {
            // 处理返回的数据
                ...state,
                isLoading: false,
                list: action.payload.list,
                errMsg: ''
            }
        case actionTypes.FETCH_BLOG_LIST_FAILED:
            return {
                ...state,
                isLoading: false,
                errMsg: '接口错误'
            }
        default:
            return state
    }
}

reducers/index.js


import { combineReducers } from 'redux'

import blog from './blog'


export default combineReducers({
    blog
})

components/BlogList/BlogList.js

import React, { PureComponent } from 'react'

import { connect } from 'react-redux'
import BlogItem from './BlogItem'

import { fetchBlogList } from '../../actions/blog'


class BlogList extends PureComponent {
    componentDidMount() {
        this.props.fetchBlogList()
    }
    render() {
        const { isLoading, list, errMsg } = this.props
        const hasErr = Boolean(errMsg)
        return (
            isLoading
                ?
                <div>isLoading</div>
                :
                (
                    hasErr
                        ?
                        <p>{errMsg}</p>
                        :
                        <div>{
                            list.map(blog => {
                                return (
                                    < BlogItem key={blog.id} {...blog} />
                                )
                            })
                        }
                        </div>
                )
        )
    }
}

const mapState = (state) => {
    return {
        list: state.blog.list,
        isLoading: state.blog.isLoading,
        errMsg: state.blog.errMsg
    }
}

export default connect(mapState, { fetchBlogList })(BlogList)

components/BlogList/BlogItem.js

import React, { PureComponent } from 'react'

export default class BlogItem extends PureComponent {

    // prop-types检测传入的数据
    render() {
        return (
            <div>
                <h3>{this.props.title}</h3>
                <p>{this.props.body}</p>
            </div>
        )
    }
}

components/BlogList/index.js

export { default as BlogList } from './BlogList/BlogList' 

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值