首次定义三种状态常量
constants/index.js
export const FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS'//成功
export const FETCH_USER_REQUEST = 'FETCH_USER_REQUEST'//等待
export const FETCH_USER_FAILURE = 'FETCH_USER_FAILURE'//请求
2.在reducers/user.js引入常量
import {FETCH_USER_SUCCESS,FETCH_USER_REQUEST,FETCH_USER_FAILURE} from '../constants/index.js'
const initialState = {
user:{},
isFetching:false,
error:null
}
const user = (state=initialState,action)=>{
switch(action.type){
case FETCH_USER_SUCCESS:
return {
user:action.user,
error:null,
isFetching:false
};
case FETCH_USER_REQUEST:
return{
isFetching:true,
error:null,
user:{}
};
case FETCH_USER_FAILURE:
return{
isFetching:false,
error:action.error,
user:{}
};
default:
return state
}
}
export default user;
3.在actions/user.js
import {FETCH_USER_SUCCESS,FETCH_USER_REQUEST,FETCH_USER_FAILURE} from '../constants/index.js'
// export function fetch_user(user){
// return{
// type:FETCH_USER_SUCCESS,
// user
// }
// }
export const fetch_user_failure=(error)=>{
return{
type:FETCH_USER_FAILURE,
error
}
}
export const fetch_user=(user)=>{
return{
type:FETCH_USER_SUCCESS,
user
}
}
export const fetch_user_request=()=>{
return{
type:FETCH_USER_REQUEST
}
}
export const get_user=()=>{
return dispatch=>{
dispatch(fetch_user_request())
fetch('http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php')
.then(res=>res.json())
.then(data=>{
dispatch(fetch_user(data.chengpinDetails[0]))
})
.catch(error=>{
dispatch(fetch_user_failure(error))
})
}
}
在页面中
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as userAction from '../reduxDemo/actions/user.js'
class User extends React.Component{
render(){
console.log(this.props)
const {error,isFetching,user} = this.props.user;
let data;
if(error){
data = error;
}else if(isFetching){
data = 'Loading....'
}else{
data = user.title
}
return(
<div>
<p>{data}</p>
<p>user</p>
<button onClick={()=>{this.props.userAction.get_user()}}>getUser</button>
</div>
)
}
}
const mapStateToProps = (state)=>{
console.log(state);
return{
user:state.user
}
}
const mapDispatchToProps=(dispatch)=>{
return{
userAction:bindActionCreators(userAction,dispatch)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(User)