如何使用React-Router根据URL /路径更新ReactJS组件
发布时间:2020-12-15 06:24:19 所属栏目:百科 来源:网络整理
导读:使用React-Router时,如何使用URL /路径更新ReactJS组件? 下面的代码工作,但这是正确的方法吗?似乎像很多代码做一个简单的更新。我希望在路由器中有一个有状态的API调用来自动处理这种情况。 var MyHomeView = React.createClass({ componentDidMount: fu
使用React-Router时,如何使用URL /路径更新ReactJS组件?
下面的代码工作,但这是正确的方法吗?似乎像很多代码做一个简单的更新。我希望在路由器中有一个有状态的API调用来自动处理这种情况。 var MyHomeView = React.createClass({ componentDidMount: function() { this.props.updateHeader(); },render: function() { return ( <div> <h2>Home</h2> </div> ); } }); var MyAboutView = React.createClass({ componentDidMount: function() { this.props.updateHeader(); },render: function() { return ( <div className="my-page-text"> <h2>About</h2> </div> ); } }); var MyHeader = React.createClass({ mixins: [ CurrentPath ],getInitialState: function() { return { myPath: "about",classes: "ion-ios7-information" }; },updateHeader: function() { // Classnames refer to www.ionicons.com if (this.getCurrentPath() === "/") { this.setState( {myPath: "about" } ); this.setState( {classes: "ion-ios7-information" } ); } else { this.setState( {myPath: "/" } ); this.setState( {classes: "ion-ios7-rewind" } ); } },render: function() { return ( <Link to={this.state.myPath}> <i className={this.state.classes} /> </Link> ); } }); var App = React.createClass({ updateHeader: function() { this.refs.header.updateHeader(); },render: function() { return ( <div> <MyHeader ref="header" /> <this.props.activeRouteHandler updateHeader={this.updateHeader} /> </div> ); } }); React.renderComponent(( <Routes> <Route path="/" handler={App}> <DefaultRoute handler={MyHomeView} /> <Route name="about" handler={MyAboutView} /> </Route> </Routes> ),document.body);
在反应路由器2.0.0中,您可以使用hashHistory或
browserHistory:
browserHistory.listen(function(ev) { console.log('listen',ev.pathname); }); <Router history={browserHistory}>{routes}</Router> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |