javascript - init 如何从 componentDidMount 更改 redux 状态?

标签 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 is not a function

self.setState({ type:'ADD_TODO' }); dont init reducer ! Why ?

reducer 代码:

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

最佳答案

您需要从您的组件进行分派(dispatch)和操作,并在reducer 中更改您的状态。

简单的例子:

组件:

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

注意事项: 从你的组件 IMO 直接发送操作对于现实世界的应用程序来说并不是真正的最佳选择,因为你耦合了你的组件。请考虑改用 containers 并更多地解耦您的应用程序。 An interesting article .

关于javascript - init 如何从 componentDidMount 更改 redux 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44452873/

相关文章:

reactjs - 使用它来存储 JSX 组件以便在其他地方显示是滥用上下文吗?

reactjs - 在 React 16 中使用 require 和 npm 在没有 npm 的情况下创建react-class

Angular + redux/ngrx : state update vs. 形式

javascript - 如何从我的 redux 操作向 GraphQL 服务器发出请求?

javascript - 检查日期字符串是否大于 3 天

javascript - Canvas 像素化 - 调整像素大小

node.js - 包含 JSON 文件作为 Webpack 输出,但不属于 bundle.js

javascript - 如何修复 Redux-React 应用程序中的这些错误?

JavaScript 间隔函数来计算日期时间

javascript - 如何快速改变演奏音调的频率而不会发出crack啪声?