返回介绍

把状态树并入 ReactJS

发布于 2025-04-26 18:09:27 字数 1625 浏览 0 评论 0 收藏

我们已经深入了解了 Baobab 是怎样工作的。但是,Baobab 的真正强大之处在于如何与 ReactJS 整合。让我们首先看一下如何把状态树和 React JS 组件结合到一起,从而可以响应树上的事件来获取数据改变。然后,我会解释为什么指定组件只去关注感兴趣的状态改变,而不是监听所有事件。

连接状态树和 React 组件有两种策略。下面我们就使用前面定义的状态树来实践一下。

将单个游标连接到组件

var stateTree = require('./stateTree.js');
var React = require('react');

var listCursor = stateTree.select('admin', 'notifications', 'list')
    ;
var myComponent = React.createClass({
  mixins: [listCursor.mixin],
  renderNotification: function(notification){
    return (
      <li>{notification.title}</li>
    );
  },
  render: function(){
    return (
      <ul>
        {this.state.cursor.map(this.renderNotification)}
      </ul>
    );
  }
});

将多个游标连接到组件

var stateTree = require('./stateTree.js');
var React = require('react');

var listCursor = stateTree.select('admin', 'notifications', 'list')
    ;
var myComponent = React.createClass({
  mixins: [listCursor.mixin],
  cursors: {
    notifications: ['admin', 'notifications', 'list'],
    feeds: ['home', 'feeds']
  },
  renderFeed: function(feed) {
    return (
      <li>{feed.title}</li>
    );
  },
  render: function(){
    return (
      <div>
        <div>You have {this.state.cursors.notifications.length}
            notifications</div>
        <ul>
          {this.state.cursors.feeds.map(this.renderFeeds)}
        </ul>
      </div>
    );
  }
});

我们已经看到将 state 连接到一个组件是多么简单。如果你想创建多个游标,可以引入一个树的全量,但是依然可以只引入一个游标用来抓取状态。当这些游标的数据发生了改变时,组件就会自动渲染,并且新的值可以通过组件的 state 对象的 cursors 或者 cursor 属性获取。

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。