原始版本
export const fetchPosts = () => {
    // dispatch: can change any data we want
    // getState: get or access any data we want
    return async function(dispatch, getState) { // can remove unused parameter
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

移除沒用到的參數
export const fetchPosts = () => {
    return async function(dispatch) { // can change to arrow function
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

改用 arrow function
export const fetchPosts = () => {
    return async (dispatch) => { // can remove round brackets because only one parameter
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

移除小括號
export const fetchPosts = () => { // can merge return function
    return async dispatch => {
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

合併 return function
export const fetchPosts = () => async dispatch => {
    { // can remove redundant 
        const response = await jsonPlaceholder.get('/posts')

        dispatch({type:'FETCH_POSTS', payload: response})
    }
}

完成
export const fetchPosts = () => async dispatch => {
    const response = await jsonPlaceholder.get('/posts')

    dispatch({type:'FETCH_POSTS', payload: response})
}


接下來看什麼

上一篇 / 下一篇
上一篇:redux - just understand more about mapStateToProps 下一篇:redux - shorten an async function
延伸閱讀
訂閱 RSS: 總經 · 技術