MobX:分配后重新发送

时间:2017-04-21 19:00:13

标签: reactjs state observable mobx

美好的一天!

我有一个父组件:

@observer
class ToDos extends Component {
  componentWillMount() {
    this.state = new State();
    this.onClearAllCompleted = this.onClearAllCompletedHandler.bind(this);
  }

  onClearAllCompletedHandler() {
    this.state.clearAllCompleted();
  }

  render() {
    const todos = this.state.todos;

    return (
      <Provider todos={todos}>
        {this.props.children}
        <ClearAllButton onClick={this.onClearAllCompleted} />
      </Provider>
    );
  }
}

并为它的州级:

class TodosState {
  @observable todos = [
    { title: 'Sleep', completed: true },
    { title: 'Sleep more', completed: false },
    { title: 'Sleep more than before', completed: false }
  ];

  @action
  clearAllCompleted() {
    this.todos = this.todos.filter(todo => !todo.completed);
  }
}

当我尝试清除所有已完成的待办事项时,它会在浏览器控制台中清除它们并发出警告:MobX Provider: Provided store 'todos' has changed. Please avoid replacing stores as the change might not propagate to all children

在此之后没有任何反应:我有旧的渲染html;(

所以,我认为孩子们有一个可观察的待办事项对象引用一个对象,并且在分配状态后我有不同的引用。孩子们不知道这一点,他们的可观察性根本没有改变。那么,在这种情况下我能做些什么呢?

1 个答案:

答案 0 :(得分:1)

问题出在<style name="tabLayoutTitles"> <item name="android:textColor">@color/white</item> <item name="android:textSize">@dimen/appFirstFontSize</item> <item name="android:fontFamily">@font/vazir_bold</item> </style> <style name="defaultTabLayout"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">@dimen/defaultTabLayoutHeight</item> <item name="android:gravity">right</item> <item name="tabTextAppearance">@style/tabLayoutTitles</item> <item name="tabSelectedTextColor">@color/white</item> <item name="tabIndicatorColor">@color/white</item> <item name="tabIndicatorHeight">@dimen/accomTabIndicatorHeight</item> <item name="tabMode">fixed</item> <item name="tabGravity">fill</item> <item name="tabBackground">@drawable/rectangle_white_ripple</item> <item name="android:background">@color/colorPrimary</item> </style> 方法中 - 在每次重新渲染时,您都会将新的render传递到todos组件中。 Provider组件是棘手的组件,它总是需要相同的道具,但每次都会传递不同的Provider数组。

更正后的代码:将整个todos对象传递到stateProvider对象在您的示例中始终相同,就像this.state想要的那样)

Provider

顺便提一下,我建议您将render() { return ( <Provider store={this.state}> {this.props.children} <ClearAllButton onClick={this.onClearAllCompleted} /> </Provider> ); } 替换为componentWillMount()。构造函数是存储初始化的更好位置。特别是在下一版本的React(16.0+)中constructor()可能会在实际安装之前为同一实例多次调用。

相关问题