ReactJS 嵌套列表 (flux)

Posted

技术标签:

【中文标题】ReactJS 嵌套列表 (flux)【英文标题】:ReactJS Nested Lists (flux) 【发布时间】:2014-12-09 12:16:12 【问题描述】:

我在搞乱 React 并且遇到了嵌套列表的问题。我有 2 个列表 - 项目和待办事项,每个待办事项上都有一个 project_id。我有 4 个与这些列表相关的组件:projects-component,它呈现一个 project-components 的列表,每个都有自己的 todos-component,并将 projectId 属性设置为项目的 ID。 todos-component 使用 TodosWatchMixin 传递 getTodos 函数,该函数依赖于 component.props.projectId 来获取待办事项列表,然后呈现第四个组件的列表:todo-component(此处未显示。)一切正常非常好,直到我将一个新项目添加到列表中。项目出现了,但待办事项发生了变化 - 新项目中包含另一个项目的待办事项,并且该项目的其他大部分待办事项似乎也发生了变化......交互(刷新或检查错误的项目)修复它 - 所以我猜想我的使用 React Chrome 开发工具我可以看到新项目上有它自己的 ID,但它也有一个项目列表......我错过了什么?

这里有一些代码sn-ps:

projects-component.js

/**
 * @jsx React.DOM
 */

var React = require('react');
var Project = require('./project-component');
var ProjectsWatchMixin = require('./projects-watch-mixin');
var ProjectStore = require('./projects-store');
var Actions = require('./project-actions');
var MasonryMixin = require('./masonry-mixin.js');
var masonryOptions = 
    transitionDuration: 0,
    itemSelector: '.project-wrap'
;


function getProjects() 
  return projects:ProjectStore.getProjects();


var Projects = React.createClass(
  displayName: 'ProjectComponent',
  mixins: [ProjectsWatchMixin(getProjects), MasonryMixin(masonryOptions)],
  loadDemoData: function() 
    Actions.loadDemoData();
  ,
  submitNewProject: function(e) 
    e.preventDefault();
    var t = this.refs.title.getDOMNode();
    if (t.value == '') return t.focus()
    Actions.addProject(title:t.value)
  ,
  render: function() 
    var projectList = this.state.projects.map(function(project, i)
      return (
        <div className="project-wrap" key=i>
          <Project model=project />
        </div>
      );
    );

    return (
      <div ref="masonryContainer" className="projects">
        <div className="project-wrap text-center">
          <div className="project">
            <header>
              <h3>New Project</h3>
            </header>
            <form onSubmit=this.submitNewProject className="input-group">
              <input type="text" className="frm-ctrl" ref="title" />
              <span className="input-group-addon">
                <button type="submit" className="btn"><i className="fa fa-plus-circle" /></button>
              </span>
            </form>
          </div>
        </div>
        <div>
          projectList
        </div>
      </div>
    );
  

);


module.exports = Projects;

project-component.js

/**
 * @jsx React.DOM
 */

var React = require('react');
var Todos = require('../todos/todos-component');

var Project = React.createClass(
  noop: function(e) 
    e.preventDefault(); // yeah, yeah... not exactly noop!
  ,
  render: function() 
    var m = this.props.model;
    var st = m.get('subTitle');
    if (st) st = <small>st</small> 
    return (
      <div className="project">
        <header>
          <h3>m.get('title') st</h3>
        </header>
        <p>m.get('description')</p>
        <Todos projectId=m.get('id') />
      </div>
    );
  
);

module.exports = Project;

todos-component.js

/**
 * @jsx React.DOM
 */

var React = require('react');
var Todo = require('./todo-component');
var TodosWatchMixin = require('./todos-watch-mixin');
var TodoStore = require('./todos-store');
// var TodoActions = require('./todo-actions');

function getTodos(component) 
  return todos:TodoStore.getTodos(component.props.projectId);


var TodoList = React.createClass(
  mixins: [TodosWatchMixin(getTodos)],

  render: function() 
    var todoList = this.state.todos.map(function(t,i)
      return <Todo key=i model=t />
    );
    return (
      <ul className="todo-list">
        todoList
      </ul>
    );
  

);

module.exports = TodoList;

projects-store.js

var Backbone = require('backbone');
var LocalStorage = require('backbone.localstorage');

var Dispatcher = require('./project-dispatcher');
var Constants = require('./project-constants');
// var Actions = require('../actions/app-actions');
var merge = require('react/lib/merge');
var EventEmitter = require('events').EventEmitter;
var TodoStore = require('../todos/todos-store');
var CHANGE_EVENT = "change";
if (window) window.Backbone = Backbone;

var Project = Backbone.Model.extend(
  localStorage: new Backbone.LocalStorage("com.thomporter.todosApp.projects"),
  defaults: 
    sort_order: 0,
    title: '',
    subTitle: '',
    description: ''
  
);

var Projects = Backbone.Collection.extend(
  model: Project,
  localStorage: new Backbone.LocalStorage("com.thomporter.todosApp.projects"),
  initialize: function()
    this.comparator = this.comparatorDefault;
    this.sort();
  ,
  comparatorDefault: function (model) 
    return model.get('sort_order');
  
);

var _projects = new Projects();

_projects.fetch();

var _demoDataLoaded = false;
function _loadDemoData () 
  if (_demoDataLoaded) return;
  _demoDataLoaded = true;
  demo = require('./demo-data');
  demo.projects.map(function(p, i)
    var todos = p.todos
    delete p.todos;
    p.id = i+1000;
    ProjectStore.addProject(p);
    if (todos) 
      todos.map(function(t)
        t.project_id = p.id;
        TodoStore.addTodo(t);

      );
    
    // _projects.sync();

  );
;
function _addProject (project) 
  if (!project.id) 
    project.id = (new Date()).getTime();
  
  var p = new Project(project);
  p.save(project, success:function()
    _projects.add(p);
    ProjectStore.emitChange();
  );
;

function _removeProject () 
  alert('Not Implemented Yet.');
;

var ProjectStore = merge(EventEmitter.prototype, 
   emitChange:function()
    this.emit(CHANGE_EVENT)
  ,
  addChangeListener:function(callback)
    this.on(CHANGE_EVENT, callback)
  ,

  removeChangeListener:function(callback)
    this.removeListener(CHANGE_EVENT, callback)
  ,

  get: function(id) 
    return _projects.get(id);
  ,

  getProjects: function() 
    return _projects;
  ,

  addProject: function(project) 
    _addProject(project);

  ,

  dipatcherIndex: Dispatcher.register(function(payload)
    var action = payload.action;
    switch(payload.action.actionType) 
      case Constants.ADD_PROJECT:
        _addProject(payload.action.project);
        return; // will emit change after save success
      case Constants.REMOVE_PROJECT:
        _removeProject(payload.action.project);
        break;
      case Constants.LOAD_DEMO_DATA:
        _loadDemoData();
        break;
    
    ProjectStore.emitChange();
    return true;
  ),

);
// _loadDemoData();
module.exports = ProjectStore;

if (window) window._projects = _projects;

你可以看到the work in progress here。点击ctrl+shift+Lcommand+shift+L 加载测试数据,然后添加一个新项目,您可能会在新项目中看到农场列表项。

【问题讨论】:

【参考方案1】:

您使用Array.map 调用的索引作为组件键。这意味着您的列表组件不能保证在每次渲染时都具有相同的键值。 React 在执行 diff 时在内部使用这些来与 DOM 进行协调,因此如果您使用数组索引作为键,则每次呈现的内容都会有所不同。它在文档中明确提到:http://facebook.github.io/react/docs/multiple-components.html#dynamic-children。

您需要根据项目的自然 ID(即,不是数组索引)分配键,并确保它们是字符串(来自上面的链接):

数字属性将按顺序排列,在其他属性之前 特性。如果发生这种情况,React 会乱序渲染组件。 这可以通过向键添加字符串前缀来避免

【讨论】:

就是这样。我实际上已经尝试过这个并且认为它不起作用,但是我将项目密钥设置为'k' + i,而不是'k' + project.get('id')。你的回答让我回去看看并注意到这一点,谢谢! =)

以上是关于ReactJS 嵌套列表 (flux)的主要内容,如果未能解决你的问题,请参考以下文章

ReactJS + Flux - 如何实现 toasts/notifications?

ReactJS 和 Flux 中的 $resource 对应项

reactjs/flux:按顺序执行动作(ajax)

如何使 reactjs/flux/react-router spa 同构?

具有 Flux 架构的 ReactJS 生成大型 JS 文件,最佳实践是啥?

如何在 Flux / ReactJS 中处理多个相同类型的商店?