首页 文章

Redux Actions必须是普通对象 . 使用自定义中间件进行异步操作

提问于
浏览
2

代码是:

Test component

import {add} from './../actions/';

class Test extends Component{

    _add = (){
       this.props.add(1);
    }

    render(){
        <button onClick={this._add}>add</button>  
    }

}

const mapStateToProps = ()=>({
    haha:'haha'
});

export default connect(
    mapStateToProps,
    {add}
)(Test)

Actions

export const add = value => (dispatch) =>{
    dispatch({
        type:'ADD',
        value:value
    })
}

我点击添加按钮有这个错误!

有什么问题?

我看了createStore.js和 console.log(action) . 它显示了一个功能 .

但Redux的例子不是函数 . 我的代码几乎一样 .

3 回答

  • 2

    如果您使用redux-thunk作为中间件,它将处理调度的函数操作....

    另一个是redux-promise,它会像thunk一样思考...但是有了承诺

    UPDATE:

    这是一个处理异步的模型

    export const add = value => (dispatch) => {
       ... do something async
    }
    

    像这样:

    export const add = value => (dispatch) => {
       http.get('/path')
           .then(json => 
               dispatch({type: 'RESULT', payload: json}));
    }
    

    你的动作没有异步调用所以它可以像这样写:

    export const add = value => ({
        type:'ADD',
        value:value
    })
    
  • 0

    你只是错过箭头函数中的箭头 =>

    export const add = value => (dispatch) => {
        dispatch({
            type:'ADD',
            value:value
        })
    }
    
  • 2

    您应该像这样编写您的动作创建者:

    export const add = value =>
      ({
        type: 'ADD',
        value: value
      });
    

    您将动作创建者连接到组件的方式(使用快捷符号 { add } 作为第二个参数传递给 connect )允许您省略 dispatch ,因为 connect 会在以这种方式调用时自动将您的动作创建者包装成 dispatch 调用 .

相关问题