2016-12-14 78 views
1

我有一個React/Redux/Firebase應用程序,我需要在呈現方法之前檢查當前用戶的用戶名,以便知道是否需要轉到數據庫並檢索其他用戶。如何在render方法之外訪問React/Redux當前用戶?

但是,由於某些原因,我不清楚,我不能在render方法外訪問this.props.currentUser。它返回null。

基本上,我想訪問這個函數內部。我的代碼如下所示:

componentDidMount() { 
    var userURL = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1'); 

    if(this.props.currentUser.username !== userURL) { 
    this.getDbUser(userURL); 
    console.log(userURL); 
    } 
} 

我得到一個錯誤

Cannot read property username of null 

我可以訪問render()數據的罰款。任何想法如何解決這將是偉大的。謝謝!

+0

機會是你的渲染方法運行兩次,在第二次運行時,用戶定義。這就是爲什麼它在渲染 – corvid

+0

工作原因,謝謝,渲染實際上運行兩次,不知道爲什麼。我在構造函數中調用了一個fetchUser方法,所以不應該在線下使用? –

+0

不是,如果是異步 – corvid

回答

1

編輯:實際上 - ComponentDidMount在異步'fetch'返回前運行,因此currentUser將是null。嘗試更改ComponentDidMountComponentWillReceiveProps(nextProps),並用'next.props'替換代碼中的'this.props'。

ComponentWillReceiveProps裏面的所有東西都會在您的道具更新爲'fetched'用戶後運行。例如:

componentWillReceiveProps(nextProps) { 
    var userURL = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1'); 

    if(nextProps.currentUser && nextProps.currentUser.username !== userURL) { 
    this.getDbUser(userURL); 
    console.log(userURL); 
    } 
} 

上面的代碼還包括在IF &&所以不會有一個錯誤,如果是currentUser null

文檔:https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

+0

不錯!這似乎工作。謝謝Shane! –

相關問題