React JS动作不起作用

时间:2018-07-06 05:23:08

标签: reactjs redux react-redux

我是新来反应js并尝试了一小段代码

import  * as template_actions from '../actions/actions'
class EmailTemplateList extends Component {
    constructor(props){
        super(props);
    }

    render(){
        console.log(this.props.template_actions.add_template({'name': 'Ramesh'}))
        return (<div>
            Welcome
        </div>);
    }

}

function mapDispatchToProps(dispatch){
    return {
        template_actions: bindActionCreators(template_actions, dispatch)
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(EmailTemplateList)

actions.js

export const ADD_EMAIL_TEMPLATE     = 'ADD_EMAIL_TEMPLATE';
export function add_template(payload){
    return dispatch => {
        dispatch({
            payload: payload,
            type: ADD_EMAIL_TEMPLATE
        });
    }
}

但是错误是

Actions must be plain objects. Use custom middleware for async actions

找不到解决方案。

3 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

return (dispatch) => {
    dispatch({
        payload: payload,
        type: ADD_EMAIL_TEMPLATE
    });
}

答案 1 :(得分:0)

import  * as template_actions from '../actions/actions'
class EmailTemplateList extends Component {
    constructor(props){
        super(props);
    }

    render(){
        console.log(this.props.add_template({'name': 'Ramesh'}))
        return (<div>
            Welcome
        </div>);
    }

}

function mapDispatchToProps(dispatch){
    return {
        add_template: payload => dispatch(template_actions.add_template(payload))
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(EmailTemplateList)

动作

export const ADD_EMAIL_TEMPLATE     = 'ADD_EMAIL_TEMPLATE';
export function add_template(payload){
    return ({
            payload: payload,
            type: ADD_EMAIL_TEMPLATE
        })
}

答案 2 :(得分:0)

我使用redux-thunk中间件解决了这个问题。