2017-06-09 2 views
1
componentDidMount(){ 
    var self = this; 

    //selt.props is undefined too from this point !!!! WHY 
    // this.props.addTodo(); 

    window.onscroll = function(){ 

     //self.setState({ type:'ADD_TODO' }); 
     // debugger 
     self.props.addTodo('param') 
    } 


} 



function mapStateToProps (state) { 
    return { 
     todos: state 
    }; 
} 

function mapDispatchToProps (dispatch, ownProps) { 



    return { 

     addTodo: function(text){ 
      dispatch({type: 'ADD_TODO', text: text, id: ++_idSeq}); 
     } 

    } 

} 

self.props.addTodo ist keine FunktionWie init ändern reduce Zustand von componentDidMount?

self.setState ({type: 'ADD_TODO'}); dont init Reduzierstück! Warum ?

Minderer Code:

function todoReducer (currentState, action) { 
    currentState = currentState || {}; // Initial State 
    // debugger 
    console.log('reducer!'); 
    switch (action.type) { 
     case 'ADD_TODO': 
      debugger 
      let newTodo = {id:1}; 
      return Object.assign({}, currentState, newTodo); 



     default: 
      return currentState; // TODO: Always return the state 
    } 
} 



// Create Store 
var todoStore = createStore(todoReducer); 

let unsubscribe = todoStore.subscribe(() => console.log(todoStore.getState())) 

window.store = todoStore; 




var TodoListContainer = connect(mapStateToProps, mapDispatchToProps)(TodoList); 
+0

Könnten Sie bitte, klären, wie Sie Projektstruktur ist? und welcher Code ist in welcher Datei? – JoseAPL

Antwort

1

Sie müssen versenden und Aktion von Ihrem component und Ihren Zustand in der reducer ändern.

Einfaches Beispiel:

Komponente:

componentWillMount() { 
    store.dispatch({ type: 'YOUR-ACTION', payload: 'yourValue' }) 
} 

Reducer:

function app(state = initialState, action) { 
    switch (action.type) { 
    case 'YOUR-ACTION': 
     // change your state here 
    default: 
     return state 
    } 
} 

Hinweise: Senden direkt aus Ihrer Komponente IMO es nicht wirklich optimal für die reale Welt-Anwendungen ist, weil Sie koppeln Ihre Komponenten. Erwägen Sie stattdessen, containers zu verwenden und Ihre App mehr zu entkoppeln. An interesting article.

Verwandte Themen