Come posso aggiornare un componente ReactJS in base a URL/percorso quando si utilizza React-Router?Come aggiornare il componente ReactJS in base a URL/percorso con React-Router
Il codice seguente funziona, ma è questo il modo corretto per farlo? Sembra un sacco di codice per fare un semplice aggiornamento. Speravo che ci sarebbe stata una chiamata API stateful nel router per occuparsi automaticamente di questo scenario.
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);
Perché mantieni "myPath" e "classe" è in stato? Dato che hai il "getCurrentPath()", potresti semplicemente calcolare i valori di link e className all'interno della funzione di rendering? O è "getCurrentPath" non aggiornato correttamente nel tuo caso? – phtrivier
Dovrò verificarlo, se 'getCurrentPath()' è in stato, allora dovrebbe funzionare senza che io tenga lo stato extra in 'myPath'. Dovrei provare questo come per esempio nei commenti di questo file: https://github.com/rackt/react-router/blob/master/modules/mixins/CurrentPath.js –