2016-10-06 41 views
0

因此,我使用React + Redux創建了一個非常簡單的CRUD風格的應用程序。有一個(讓我們打電話給他們)帖子和一個API的集合,我希望能夠列出這些,然後當用戶點擊一個,進入關於該帖子的詳細頁面。在redux中爲簡單的CRUD應用程序構造reducer

所以我有一個職位減速機。最初,我開始使用從redux現實世界例子中取得的方法。這通過索引簡化器來維護對象的緩存,當你做一個「get post」時,它會檢查緩存,如果它存在,它會返回該緩存,否則它會進行適當的API調用。當組件掛載時,它們試圖從緩存中獲取東西,如果它們不在那裏,它們會等待(返回false)直到它們結束。

雖然這工作正常,由於各種原因,我現在需要使這種非緩存,即每次我加載/ posts /:postId頁面我需要通過API獲取帖子。

我意識到,在non-redux世界中,您只需在componentDidMount中執行fetch(),然後在其上執行setState()。但是我希望帖子存儲在reducer中,因爲應用程序的其他部分可能會調用修改這些帖子的操作(比如websocket或者只是一個複雜的與redux連接的組件)。

一種方法我見過的人使用在他們的減速「活動」項目,類似這樣的例子:https://github.com/rajaraodv/react-redux-blog/blob/master/public/src/reducers/reducer_posts.js

雖然這是好的,它需要每個加載活動後必須有一個componentWillUnmount組件重置活動帖子的操作(請參閱resetMe:https://github.com/rajaraodv/react-redux-blog/blob/master/public/src/containers/PostDetailsContainer.js)。如果它沒有重置活動帖子,它將在顯示下一篇文章時留下來(在API調用時它可能會短時間閃爍,但它仍然不好)。通常強迫每個想看帖子的頁面在componentWillUnmount中執行resetMe()都會變得像惡臭。

那麼有沒有人有任何想法或見過這樣的一個很好的例子?這似乎是一個簡單的例子,我有點驚訝,我找不到任何材料。

+0

你是什麼意思「如果它沒有重置活動帖子」?你能提供一個真實的用例嗎? –

回答

0

如何做到這一點取決於你現有的減速,但我只會做一個新的

reducers/post.js

import { GET_ALL_POSTS } from './../actions/posts'; 

export default (state = { 
    posts: [] 
}, action) => { 
    switch (action.type) { 
    case GET_ALL_POSTS: 
     return Object.assign({}, state, { posts: action.posts }); 
    default: 
     return state; 
    } 
}; 

這是很容易理解的,只是火到行動獲取您的所有帖子,並用減速器中的新帖子替換之前的帖子。

使用componentDidMount來觸發GET_ALL_POSTS動作,並在狀態中使用布爾型標誌來知道是否加載的帖子,所以你不會每次都重新加載它們,只有當組件加載時。

components/posts.jsx

import React from 'react'; 

export default class Posts extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     firstLoad: false 
    }; 
    } 

    componendDidMount() { 
    if (!this.state.firstLoad) { 
     this.props.onGetAll(); 
     this.setState({ 
      firstLoad: true 
     }); 
    } 
    } 

    // See how easy it is to refresh the lists of posts 
    refresh() { 
    this.props.onGetAll(); 
    } 

    render() { 
    ... 

    // Render your posts here 
    { this.props.posts.map(...) } 
    ... 
    } 
} 

我們只是缺少容器的職位和事件傳遞到組件

containers/posts.js

import { connect } from 'react-redux'; 
import { getPosts } from './../actions/posts'; 
import Posts from './../components/posts.jsx'; 

export default connect(
    state => ({ posts: state.posts }), 
    dispatch => ({ onGetAll:() => dispatch(getPosts()) }) 
); 

這是一個非常簡單的模式,我用它在許多應用程序tions

0

如果您使用react-router,您可以利用onEnter鉤子。

相關問題