Time: 20200129
截屏2020-01-29下午4.54.36.png异步Action Creator需要用到同步Action Creator.
完整代码如下:
const redux = require('redux')
const createStore = redux.createStore
const applyMiddleware = redux.applyMiddleware
const thunkMiddleware = require('redux-thunk').default
const axios = require('axios')
// state
const initialState = {
loading: false,
users: [],
error: ''
}
// action
const FETCH_USERS_REQUEST = 'FETCH_USERS_REQUEST'
const FETCH_USERS_SUCCESS = 'FETCH_USERS_SUCCESS'
const FETCH_USERS_FAILURE = 'FETCH_USERS_FAILURE'
// action creator
const fetchUsersRequest = () => {
return {
type: FETCH_USERS_REQUEST,
}
}
const fetchUsersSuccess = users => {
return {
type: FETCH_USERS_SUCCESS,
payload: users
}
}
const fetchUsersFailure = error => {
return {
type: FETCH_USERS_FAILURE,
payload: error
}
}
// reducers
const reducer = (state=initialState, action) => {
switch (action.type) {
case FETCH_USERS_REQUEST:
return {
...state,
loading: true,
}
case FETCH_USERS_SUCCESS:
return {
...state,
loading: false,
users: action.payload,
}
case FETCH_USERS_FAILURE:
return {
...state,
loading: false,
error: action.payload,
}
default:
return state
}
}
// const fetchUsersAsync = () => {
// return function(dispatch) {
// dispatch({type: FETCH_USERS_REQUEST})
// axios.get('https://jsonplaceholder.typicode.com/users')
// .then(response => {
// // response.data is the list of users
// dispatch({type: FETCH_USERS_SUCCESS, payload: response.data})
// })
// .catch(error => {
// dispatch({type: FETCH_USERS_FAILURE, payload: error.message})
// })
// }
// }
const fetchUsersAsync = () => {
return function (dispatch) {
dispatch(fetchUsersRequest())
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
// response.data is the list of users
const users = response.data.map(user => user.id)
dispatch(fetchUsersSuccess(users))
})
.catch(error => {
const message = error.message
dispatch(fetchUsersFailure(message))
})
}
}
const store = createStore(reducer, applyMiddleware(thunkMiddleware))
store.subscribe(() => console.log(store.getState()))
store.dispatch(fetchUsersAsync())
执行结果:
{ loading: true, users: [], error: '' }
{
loading: false,
users: [
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
],
error: ''
}
用上redux-thunk
后,我们就可以构建异步Action Creator,上面的fetchUserAsync
就是这样一个函数,它需要返回一个新的函数,并接收dispatch
作为参数,并在适当的时机dispatch
同步行为。
END.
网友评论