javascript - ReactRouter的组件通信问题?
PHP中文网
PHP中文网 2017-04-11 12:23:06
[JavaScript讨论组]

路由是这样的


  
    
  

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 (
      

// .... {this.props.children}

); }, });

然后AppIndex是这样的

const AppIndex = React.createClass({
  render: function() {
    console.log("render AppIndex");
    console.log(this.props.id);
    return 

{this.props.id || "NULL"}

; }, });

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

render App
render AppIndex
null
render App

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

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

PHP中文网
PHP中文网

认证0级讲师

全部回复(2)
PHP中文网
{this.props.children && React.cloneElement(this.props.children, {
    id: this.state.id
})}

id传递至子组件props中。

天蓬老师

好几处问题,这和 route 没关系

  1. 那四和输出,前两应该你也理解了,第三行肯定输出 null 啊,state.id 初始化是本来就是 null,你用$.get 异步赋值前 AppIndex 早就 render 了,这时候肯定是 null 啊;

  2. $.get 异步给 state 赋值,此时App会 render,所以会有第四行的输出;

  3. this.props.children.props.id = this.state.id; 不建议这样传值,props 规范是只读,实际这样做也是错的;

  4. 你那个$.get 获取的数据只是在 AppIndex 里用,为什么不放在 AppIndex 里呢?

你先看看 reactjs 好的例子,理解一下思路。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号