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

react-redux使用(发送请求时)_第1张图片

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(
    
        
    , document.getElementById('root')
)


App.js



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

export default class App extends PureComponent {

    render() {
        return (
            
) } }

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
                ?
                
isLoading
: ( hasErr ?

{errMsg}

:
{ list.map(blog => { return ( < BlogItem key={blog.id} {...blog} /> ) }) }
) ) } } 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 (
            

{this.props.title}

{this.props.body}

) } }

components/BlogList/index.js

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

react-redux使用(发送请求时)_第2张图片

你可能感兴趣的:(react,react)