2017-04-21 7 views
0

おはよう!そのため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> 
    ); 
    } 
} 

と国家クラス:MobX Provider: Provided store 'todos' has changed. Please avoid replacing stores as the change might not propagate to all children

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); 
    } 
} 

私はすべて完了したドスをクリアしようと、それは彼らが、ブラウザのコンソールに警告をクリアし

は私が親コンポーネントを持っています。この何も後

が起こる:私は古いレンダリングされたHTMLを持っている。(

をだから、私は子供が一つのオブジェクトへの参照ドスの観察可能なオブジェクトを持っており、状態の割り当てた後、私は別の参照を持っていると思いチャイルズが知ってはいけません。 。この、およびその観察可能な、私はこのケースで何ができるか、だから、全く変わっていません

答えて

1

問題がrender方法である - ?。各再レンダリングあなたがProviderコンポーネントに新しいtodosを渡すにProviderコンポーネントは注意が必要です常に同じ小道具を必要とするコンポーネントですが、毎回異なるtodos配列を渡します。

修正されたコード:私はあなたがconstructor()componentWillMount()を交換をお勧めしますちなみに(this.stateオブジェクトがProviderが望んでいると同じように、あなたの例では常に同じである)Provider

render() { 

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

を全体stateオブジェクトを渡します。コンストラクターはストアの初期化に適しています。特にReact(16.0+)の次のバージョンでは、実際にマウントされる前に同じインスタンスに対して複数回呼び出される可能性があります(componentWillMount())。

関連する問題