2016-09-08 40 views
1

在我的React + Redux客戶端應用程序中,我需要獲取活動用戶信息(從myapp.com/users/me獲取)並將其保留在某處以便我可以從多個組件訪問它。在React + Redux客戶端應用程序上保留活動用戶數據的位置

我猜window.activeUser = data不是最好的做法。但是我找不到有關這樣做的最佳做法的任何資源。什麼是做我想要的最好的方式?

回答

3

您可以將其保留在單獨的縮減器中,然後在組件中將connect()的狀態的多個部分導入。

如果您在設置商店時設置了2個稱爲users.jstags.js的減速器,並將它們與combineReducers結合使用。您只需將功能傳遞給您的connect()調用即可拉出不同的部分。因此,使用ES6 +裝飾:

const mapStateToProps = state => { 
    return {users: state.users, tags: state.tags} 
} 

@connect(mapStateToProps) 
export default class MyComponent extends React.Component { 

,然後倒在你的render功能:

return (
    <div> 
    <p>{this.props.users.activeUsernameOrWhatever}</p> 
    <p>{this.props.tags.activeTags.join('|')}</p> 
    </div> 
); 

所以你不同的減速狀態成爲this.props對象。

2

您可以使用陣營的context,110C或全局變量,使您的數據提供給多個組件,通過上下文

喜歡的東西...

class ParentDataComponent extends React.Component { 
    // make data accessible for children 
    getChildContext() { 
    return { 
     data: "your-fetchet-data" 
    }; 
    } 

    render() { 
    return < Child /> 
    } 
} 

class Child extends React.Component { 
    render() { 
    // access data from Parent's context 
    return (<div> {this.context.data} </div>); 
    } 
} 
1

創建行動的創建者,並調用它componentWillMount的適當組件,以便在組件裝入之前運行,並在動作創建者獲取需要的數據並將其傳遞給reducer。在減速器中,您可以在整個應用程序中保留所需的數據。所以無論何時您需要數據,您都可以從redux狀態中檢索數據。官方的redux網站的教程涵蓋了你需要知道的一切。如果您有任何問題,請提及我。

相關問題