2017-04-04 58 views
0

我有一個使用JWT令牌進行登錄和驗證的用戶,並通過令牌獲取他。我的問題是如何從數據庫中獲取他後呈現div。我想顯示登錄用戶的信息。如何在從React&Redux&Thunk獲取端點數據後呈現div

export function getUser() { 
    return dispatch => { 
    return axios.get('/api/user').then(res => dispatch({ 
     type: 'FETCH_PROFILE', 
     data: res.data 
    })); 
    } 
} 

和響應是一個JSON格式

{ 
"user":{ 
    "email":"[email protected]", 
    "id":1, 
    "username":"someusername" 
} 
} 

所以之後我得到的Json與登錄的用戶,我有渲染,以便在div來顯示他的證件,就像一個輪廓頁。取而代之的是我收到以下錯誤

Uncaught TypeError: Cannot read property 'map' of undefined at ProfilePage.render (ProfilePage.js:28)

componentDidMount() { 
    this.props.getUser(); 
} 

renderUser({email, username}){ 
    return (
    <div className="row"> 
     <div className="col-md-4 col-md-offset-4"> 
      {email} {username} 
     </div> 
    </div> 
); 
} 

render() { 
    const { profileUpdateRequest, addFlashMessage, getUser } = this.props; 
    return (
    <div className="row"> 
     <div className="col-md-4 col-md-offset-4"> 
      {this.props.user.map(this.renderUser)} 
      <ProfileForm 
      profileUpdateRequest={profileUpdateRequest} 
      addFlashMessage={addFlashMessage} 
      getUser={getUser} 
      /> 
     </div> 
    </div> 
); 

}

+1

你的問題不清楚,請你詳細說明 –

+0

@TusharKotlapure他的問題似乎很清楚:/ –

+0

首先檢查是否存在道具名稱用戶,然後使用地圖功能。即this.props.user? this.props.user.map():null,map也不會在你的問題中返回任何值。 –

回答

0

你需要派遣您的用戶存儲到您的終極版商店的操作。一個例子就是這樣。由於Axios使用承諾,因此您需要使用Promise/get請求的then子句進行操作。

export function getUser() { 
    return dispatch => { 
    return axios.get('/api/user').then(res => dispatch(storeUser(res))) 
    } 
} 

之後,您需要將您的調度方法映射到組件屬性。你應該這樣做:http://redux.js.org/docs/basics/UsageWithReact.html#implementing-container-components

其次,如果需要,你可以在你的渲染方法中使用快速類型檢查。

{(this.props.user && this.props.user.map(this.renderUser)) || ""} 

這不是很漂亮,但它完成了工作。

+0

我添加了一個發送。我不明白到底是什麼店用戶 –

+0

@Nickbo這是一個人爲的行動。你的減員應該知道如何處理你的行爲。我建議閱讀關於[reducers]的redux文檔(http://redux.js.org/docs/basics/Reducers.html)和[actions](http://redux.js.org/docs/basics/Actions。 HTML) –

相關問題