2016-08-08 14 views
0

我正在使用一個簡單的用戶頁面,其中每個用戶都有自己的配置文件。 配置文件頁面在初始加載時工作。單擊反應路由器中的鏈接時,組件獲取錯誤的道具

但是,如果我當前觀看USER1配置文件,然後單擊鏈接帶我去用戶2,個人資料頁仍然會加載USER1因爲this.props.params還沒有更新。如果我點擊兩次鏈接,則會顯示user2的配置文件。我需要幫助得到這個工作正常

這裏,代碼比語言更多:

var { Router, Route, Redirect, IndexRoute, IndexLink, Link, hashHistory, browserHistory } = ReactRouter; 
var browserHistory = ReactRouter.browserHistory; 


var Profile = React.createClass({ 
    getInitialState: function() { 
     return { 
      userName: '', 
      userId: '', 
      displayName: '' 
     }; 
    }, 
    setProfile: function() { 
     $.post('/api/v1/rest/getUser', {username: this.props.params.name}, function (result) { 
      if(!result.error) { 
       this.setState({ 
        userName: result.seo_name, 
        userId: result.member_id, 
        displayName: result.display_name 
       }); 
      } 
     }.bind(this)); 
    }, 
    componentDidMount: function() { 
     this.setProfile(); 
    }, 
    componentWillReceiveProps: function() { 
     this.setProfile(); 
    }, 
    render: function() { 
     return (
      <div> 
       {this.state.displayName} 
      </div> 
     ); 
    } 
}); 

var MainLayout = React.createClass({ 
    render() { 
     return (
      <div className="application"> 
       <header> 
        {this.props.children.props.route.title} 
       </header> 
       <nav> 
        <Link to="/profile/user1">User 1</Link> 
        <Link to="/profile/user2">User 2</Link> 
       </nav> 
       {this.props.children} 
      </div> 
     ) 
    } 
}); 

ReactDOM.render((
    <Router history={ReactRouter.browserHistory}> 
     <Route component={MainLayout}> 
      <Route name="profile" path="/profile/:name" title={'Viewing profile'} component={Profile} /> 
     </Route> 
    </Router> 
), document.getElementById('application')); 

正如你可以看到我使用jQuery的Ajax調用,我已經添加了在測試兩個環節MainLayout組件的導航欄。每當我去一個新的配置文件,我想重新運行ajax調用,並立即獲取新的配置文件信息。

另一個小問題:在MainLayout組件內部,我使用Route元素上定義的道具(this.props.children.props.route.title)在頁眉中打印標題。目前這說「查看配置文件」。我希望它說「查看用戶名配置文件」,其中用戶名是一個變量。我找不出一個乾淨的反應方式來做到這一點(附加一些東西到父組件的標題)。

回答

1

這裏有兩個建議:中

  1. 命名爲getProfile代替setProfile ...
  2. getProfile功能應採取一個PARAM,而不是依賴於上下文)

解決方案:

componentWillR eceiveProps意味着新的道具將被設置..所以他們還沒有設置。然而nextProps可用。

componentDidMount: function() { 
    // use the name from props to get the profile 
    this.getProfile(this.props.params.name) 
}  

componentWillReceiveProps: function(nextProps) { 
    // use the name from nextProps to get the profile 
    this.getProfile(nextProps.params.name); 
}, 

getProfile: function(name) { 
    // ajax call, use the *name* param 
} 
  • 關於產品的標題
  • 有一個名爲頭盔組件,其特別改變那些之類的東西標題

    https://github.com/nfl/react-helmet

    相關問題