4

Flux TodoMVC 为例,假设我想要两个 Todo-Apps 并排放置。

class TwoTodos extends React.Component {
  render () {
    return (
      <div>
        <TodoApp />
        <TodoApp />
      </div>
    );
  }
}

现在,当您运行此示例时,您会注意到两个 Todo 列表将同步,因为它们发出和侦听相同的操作。

防止这种情况的规范方法是什么?

4

1 回答 1

0

我刚刚解决了这个问题。我花了几天时间才弄明白。

通常,您应该将您的操作和存储设置为类,而不是可以在 Todo 组件之间共享的普通对象。然后在每个 Todo 组件中创建动作类和存储类的实例。

为避免组件相互影响,您需要将可以被不同组件实例共享的公共变量(如 TodoStore.js 中的 _todos)封装到您的 store 类中。

然后你需要将 app.js 中渲染的内容包装到一个类中,并在使用之前创建这个类的实例。

我将把关键更改放在下面的代码中。

TodoActions.js:

var Actions = function(){
    //if you have any shared variables, just define them here, instead of outside of the class 

    this.getAction = function(){
        return TodoActions;
    } 
    var TodoActions = {...};
    ...
}
module.exports = Actions;

TodoStore.js:

//private functions
function create(text, todos){...}
function update(id, updates, todos){...}

var Store = function(){
    var _todos = {};
    this.getStore = function(){
        return TodoStore;
    }   

    var TodoStore = assign({}, EventEmitter.prototype, {...});
};
module.exports = Store;

TodoApp.react.js:

var TodoApp = React.createClass({
    Store: function(){},
    Actions: function(){},
    componentWillMount: function(){
        var store = require('path/to/TodoStore.js');
        var storeInstance = new store();
        this.Store = storeInstance.getStore();  

        var action = require('path/to/TodoActions.js');
        var actionInstance = new action();
        this.Store = actionInstance .getAction();  

        this.Store.addChangeListener(...);
    }
    //If you need to call methods in Actions, just call this.Actions.<method_name>
});    
module.exports = TodoApp;

应用程序.js:

var TodoApp = require('./components/TodoApp.react');
window.Todo = function(){
    var todo = null; //In case you need to get/set the component
    this.use = function(elementId){
        todo = ReactDom.render(
            <TodoApp />,
            document.getElementById(elementId)
        )
    }
};

索引.html:

<section id="todoapp1"></section>
<section id="todoapp2"></section>
<script>
    var todo1 = new Todo();
    var todo2 = new Todo();
    todo1.use('todoapp1');
    todo2.use('todoapp2');
</script>
于 2016-09-13T01:18:03.133 回答