美文网首页
redux数据操作

redux数据操作

作者: Volon | 来源:发表于2019-06-20 17:38 被阅读0次

    action,reducer,store与页面之间的数据传递

    action代码:

    import axios from"axios";
    const url="http://localhost:3000/users";
    export const GET_POSTS="GET_POSTS"
    export function getPost(){      
            let request=axios.get(url)
                    return{
                        type:GET_POSTS,
                        payload:request
                    }
    
            }
    

    reducer代码:
    rootReducer组件

    
    
    import { combineReducers } from 'redux'
    import {GET_POSTS} from "../actions/index";
    const defaultState = {
        posts:[]
    }
     function posts (state = defaultState, action) {
        switch (action.type) {
            case GET_POSTS:
                return {
                    posts:action.payload.data
                }
            default:
                return state;
        }
    }
    const rootReducer=combineReducers({
        posts:posts
    });
    export default rootReducer
    

    store代码:

    import { createStore,applyMiddleware } from 'redux'
    import rootReducer from '../reducers'
    import ReduxPromise from "redux-promise"
    const creatStoreWidthMiddleware=applyMiddleware(ReduxPromise)(createStore);
    export default function configureStore(initialState) {
        const store = creatStoreWidthMiddleware(rootReducer,initialState)
        return store 
    }
    

    dome代码:

    import React from "react";
    import {connect} from "react-redux";
    import {getPost} from "../actions/index"
     class Dome5 extends React.Component{
        constructor(props){
            super(props);
        }
        componentWillMount(){
            this.props.getPost();
        }
        render(){   
            console.log(this.props.postList)    
            return(
                <div>
                    {this.props.postList.map((post,index)=>{
                        return(
                        <div key={index}>
                        <span>姓名:{post.firstName}</span>
                        <span>年龄:{post.age}</span>
                        </div>
                        )
                    })}
                </div>
            )
        }   
    }
    function mapStateToProps(store){
        return{
            postList:store.posts.posts
        }
    }
    export default connect(mapStateToProps,{getPost})(Dome5)
    
    

    [图片上传失败...(image-cddf40-1561023510530)]

    相关文章

      网友评论

          本文标题:redux数据操作

          本文链接:https://www.haomeiwen.com/subject/zdwjqctx.html