javascript - ReactRouter的组件通信问题?

查看:135
本文介绍了javascript - ReactRouter的组件通信问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

路由是这样的

<Router history={hashHistory}>
  <Route path="/" component={App}>
    <IndexRoute component={AppIndex} />
  </Route>
</Router>

App代码是这样的

const App = React.createClass({
  getInitialState: function() {
    return {id: null};  
  },
  componentDidMount: function() {
    $.get("api", function(data) {
      if (this.isMounted()) this.setState(data);
    }.bind(this));
  },
  render: function() {
    // 这个是想了好久想到的通过App给AppIndex组件传递数据的方式
    this.props.children.props.id = this.state.id;
    console.log("render App");
    return (
      <div>
        // ....
        {this.props.children}
      </div>
    );
  },
});

然后AppIndex是这样的

const AppIndex = React.createClass({
  render: function() {
    console.log("render AppIndex");
    console.log(this.props.id);
    return <div>{this.props.id || "NULL"}</div>;
  },
});

这样子运行之后,控制台的输出为

render App
render AppIndex
null
render App

页面中AppIndex显示的是NULL,除非点击AppIndex的路由导致AppIndexrender才会正确显示id属性。

到底这个AppAppIndex应该怎么样通信?或者如何在App重新渲染的时候自动重新渲染AppIndex哪怕路由没有改变?

解决方案

{this.props.children && React.cloneElement(this.props.children, {
    id: this.state.id
})}

id传递至子组件props中。

这篇关于javascript - ReactRouter的组件通信问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆