init如何从componentDidMount更改redux状态?

时间:2017-06-09 08:26:07

标签: javascript reactjs redux

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 不是函数

     

self.setState({type:'ADD_TODO'}); 不要使用init reducer !为什么?

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

1 个答案:

答案 0 :(得分:1)

您需要从component发送和操作,并在reducer中更改您的状态。

简单示例:

组件:

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

减速机:

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

注意: 从您的组件IMO直接发送动作对于真实世界的应用程序而言并不是最佳选择,因为您将组件结合在一起。请考虑使用containers并更多地解耦您的应用。 An interesting article