Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React路由器:传播路由组件道具/状态的真正方式_Javascript_Reactjs_React Router_Flux - Fatal编程技术网

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>
    );
  }
});