Reputation: 11184
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 is not a function
self.setState({ type:'ADD_TODO' }); dont init reducer ! Why ?
reducer 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);
Upvotes: 1
Views: 1022
Reputation: 73938
You need to dispatch and action from your component
and change your state in the reducer
.
Simple example:
Component:
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
}
}
Notes:
Sending directly actions from your component IMO it is not really optimal for real world apps, because you couple your components. Consider instead to use containers
and decoupling your app more. An interesting article.
Upvotes: 2