2017-04-16 68 views
0

我有我的異步行爲的問題。我想在action fetchPosts()被調用時將'loading'狀態設置爲true,並且當fetchPostsSuccess()或fetchPostsFailiure()時將'loading'狀態設置爲false。請求完成後觸發Redux異步操作。爲什麼?

使用我當前的代碼,當fetchPosts()接收來自服務器的響應時,它的工作幾乎沒有問題,除了'正在加載'狀態改變,我想在請求開始時改變這個狀態。

下面是顯示我的步驟的簡單代碼。 我使用的是axios和redux-promise(https://github.com/acdlite/redux-promise)。

// actions 
export function fetchPosts() { 
    const request = axios.get(`${API_URL}/posts/`); 
    return { 
    type: 'FETCH_POSTS', 
    payload: request, 
    }; 
} 

export function fetchPostsSuccess(posts) { 
    return { 
    type: 'FETCH_POSTS_SUCCESS', 
    payload: posts, 
    }; 
} 

export function fetchPostsFailure(error) { 
    return { 
    type: 'FETCH_POSTS_FAILURE', 
    payload: error, 
    }; 
} 


// reducer 
const INITIAL_STATE = { 
    posts: [], 
    loading: false, 
    error: null, 
} 
const postsReducer = (state = INITIAL_STATE, action) => { 
    switch (action.type) { 
    case 'FETCH_POSTS': 
     return { ...state, loading: true, error: null }; 
    case 'FETCH_POSTS_SUCCESS': 
     return { ...state, posts: action.payload, loading: false }; 
    case 'FETCH_POSTS_FAILURE': 
     return { ...state, posts: [], loading: false, error: action.payload }; 
    default: 
     return state; 
    } 
} 

const rootReducer = combineReducers({ 
    postsList: postsReducer, 
}); 


// store 
function configureStore(initialState) { 
    return createStore(
    rootReducer, 
    applyMiddleware(
     promise, 
    ), 
); 
} 
const store = configureStore(); 


// simple Posts app 
class Posts extends Component { 
    componentWillMount() { 
    this.props.fetchPosts(); 
    } 

    render() { 
    const { posts, loading } = this.props.postsList; 
    return (
     <div> 
     {loading && <p>Loading...</p>} 
     <ul> 
      {posts.map(post => <li key={post.id}>{post.title}</li>)} 
     </ul> 
     </div> 
    ); 
    } 
} 

const mapStateToProps = state => ({ 
    postsList: state.postsList, 
}); 

const mapDispatchToProps = dispatch => ({ 
    fetchPosts: (params = {}) => { 
    dispatch(fetchPosts()) 
     .then((response) => { 
     if (!response.error) { 
      dispatch(fetchPostsSuccess(response.payload.data)); 
     } else { 
      dispatch(fetchPostsFailure(response.payload.data)); 
     } 
     }); 
    }, 
}); 


const PostsContainer = connect(mapStateToProps, mapDispatchToProps)(Posts); 

// main 
ReactDOM.render((
    <Provider store={store}> 
    <Router history={browserHistory}> 
     <Route path="posts" component={PostsContainer} /> 
    </Router> 
    </Provider> 
), document.getElementById('appRoot')); 

有人能指導我什麼,我做錯了什麼?

回答

0

事實證明,問題出現在'redux-promise'包中。這種異步中間件沒有類似於「待定」承諾狀態的東西(稱爲「樂觀更新」)。

只有在承諾已解決或拒絕時纔會更改狀態。

我應該使用不同的中間件,允許對「樂觀更新」

0

您的問題redux-promise是。您應該使用redux-thunk,它允許您返回一個函數並分派多次。看看它 ;)!

+0

謝謝, 事實上,它是減少承諾的問題。我發現redux-promise-middleware是我所需要的。 – user7875611