我有一個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()
數據的罰款。任何想法如何解決這將是偉大的。謝謝!
機會是你的渲染方法運行兩次,在第二次運行時,用戶定義。這就是爲什麼它在渲染 – corvid
工作原因,謝謝,渲染實際上運行兩次,不知道爲什麼。我在構造函數中調用了一個fetchUser方法,所以不應該在線下使用? –
不是,如果是異步 – corvid