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)]
网友评论