使用React-Router时,如何使用URL /路径更新ReactJS组件?
下面的代码工作,但这是正确的方法吗?似乎像很多代码做一个简单的更新。我希望在路由器中有一个有状态的API调用来自动处理这种情况。@H_404_2@
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:
原文链接:https://www.f2er.com/react/301372.htmlbrowserHistory.listen(function(ev) { console.log('listen',ev.pathname); }); <Router history={browserHistory}>{routes}</Router>