Javascript React路由器:传播路由组件道具/状态的真正方式
问题:通过Javascript React路由器:传播路由组件道具/状态的真正方式,javascript,reactjs,react-router,flux,Javascript,Reactjs,React Router,Flux,问题:通过位置.状态传递组件道具/状态不是一种反模式吗?你能建议一个更好的方法吗 我有一些社交网站,每个用户都可以创建自己的个人资料。每个配置文件都是一个UserProfile组件,其路由如下: ReactDOM.render(( <Router history={History}> <Route path="/" component={App}> <IndexRoute component={Welcome} /&g
位置.状态传递组件道具/状态不是一种反模式吗?你能建议一个更好的方法吗
我有一些社交网站,每个用户都可以创建自己的个人资料。每个配置文件都是一个UserProfile
组件,其路由如下:
ReactDOM.render((
<Router history={History}>
<Route path="/" component={App}>
<IndexRoute component={Welcome} />
<Route path="profile" component={UserProfile} />
</Route>
</Router>
), document.getElementById('app'));
并在UserProfile
处检索response
:
module.exports = React.createClass({
render() {
// QUESTION: isn't it an anti-pattern? Is there any better way?
const state = this.props.location.state,
username = state.username,
............
}
})
如果您处理通过ID区分的配置文件,最好的方法是在URL中包含ID:
ReactDOM.render((
<Router history={History}>
<Route path="/" component={App}>
<IndexRoute component={Welcome} />
<Route path="profile/:userId" component={UserProfile} />
</Route>
</Router>
), document.getElementById('app'));
ReactDOM.render((
<Router history={History}>
<Route path="/" component={App}>
<IndexRoute component={Welcome} />
<Route path="profile/:userId" component={UserProfile} />
</Route>
</Router>
), document.getElementById('app'));
var UserProfile = React.createClass({
getInitialState: function() {
return {
data: null,
};
},
componentDidMount: function() {
// Your code for fetching user data from server:
Service.getUserSummary(this.props.params.userId).then(response => {
if (this.isMounted()) {
this.setState({
data: response.data
});
}
});
},
render: function() {
if (!this.state.data) {
// Rendering stage (2)
return (<div>Loading...</div>);
}
// Rendering stage (3)
return (
<div>
I am {this.state.data.userName}!
</div>
);
}
});