javascript - Components gets the wrong props when clicking links in React-router -
i'm working on simple user page each user has own profile. profile page works on initial load.
however, if viewing profile of user1 click link take me user2, profile page still load user1 because this.props.params
haven't updated yet. if click link twice, profile of user2 show up. need getting work correctly
here, code speaks more words:
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'));
as can see i'm using jquery ajax calls, , i've added 2 links testing in nav of mainlayout component. every time go new profile, want re-run ajax call , fetch new profile information instantly.
another short question: inside mainlayout component, i'm printing title of page in header using props defined on route element (this.props.children.props.route.title
). says "viewing profile". want "viewing profile of username", username variable. couldn't figure out clean react way (appending title of parent component).
here 2 suggestions:
- name getprofile instead of setprofile..
- getprofile function should take param, , not rely on context ;)
solution:
componentwillreceiveprops means new props going set.. not set yet. nextprops available.
componentdidmount: function() { // use name props profile this.getprofile(this.props.params.name) } componentwillreceiveprops: function(nextprops) { // use name nextprops profile this.getprofile(nextprops.params.name); }, getprofile: function(name) { // ajax call, use *name* param }
- question title
there component called helmet, specially change things title
Comments
Post a Comment