检查http是成功还是失败Reactjs

时间:2016-12-25 18:01:09

标签: reactjs

我想问一下,如果我的组件成功或失败的http请求,我该如何处理?我通过我的动作(http)中的reducer来调度数据。我想在这里实现的是在http请求之后组件将通知它是成功还是失败所以如果完成http请求我可以做其他事情。

组件:

class BoardAdd extends React.Component {


    addBoard(formProps) {

        // This is where my HTTP request
        this.props.addBoard(formProps);

        // After I call the this.props.addBoard(formProps). I want to check if it succeeds or fail
    }

    render() {

        const { error, handleSubmit } = this.props;

        return (
            <Col lg={3}>
                <a href="javascript:;" className={style.boardItemAdd} onClick={this.openAddBoardModal.bind(this)}>
                    <div className={[style.boardItemContainer,style.boardItemGray].join(' ')}>
                        Create New Board
                    </div>
                </a>

                <Modal show={this.state.boardAddModalShow} onHide={this.closeAddBoardModal.bind(this)} bsSize="small" aria-labelledby="contained-modal-title-sm">
                    <Modal.Header closeButton>
                        <Modal.Title id="contained-modal-title-sm">Create Board</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <form onSubmit={handleSubmit(this.addBoard.bind(this))}>

                            <Field name="name" component={renderField} type="text" placeholder="What are you organizing" />
                            <button className="btn btn-primary btn-block">Submit</button>
                        </form>

                    </Modal.Body>
                </Modal>

            </Col>
        )
    }
}

function mapStateToProps(state){
    return {
        data: state.board.data,
        success: state.board.success
    };
}

export default connect(mapStateToProps, { addBoard })(form(BoardAdd));

动作:

export function addBoard(data){
    return function(dispatch){
        axios.post(`${API_URL}/boards`,
            {
                name: data.name
            }
        )
        .then(response => {
            if(response.status === 201){
                dispatch({ type: ADD_BOARD_SUCCESS, data: response.data.result });
            }
        })
        .catch(function (error) {
            console.log(error);
        });
    }
}

减速机:

import { ADD_BOARD_SUCCESS,ADD_BOARD_FAIL} from 'constant/board.jsx';

const INITIAL_STATE = {
    data: {},
    error_message: '',
    success: false
};

export default (state = INITIAL_STATE, action = {}) => {
    switch(action.type) {
        case ADD_BOARD_SUCCESS:
            return {
                data: action.data,
                success: true,
                error_message: ''
            };
        case ADD_BOARD_FAIL:
            return {
                data: {},
                success: false,
                error_message: action.error_message
            };
        default: return state;
    }
}

1 个答案:

答案 0 :(得分:2)

通知您的组件是成功还是失败的一种方法是让您的操作返回承诺。所以你的行动将是这样的:

export function addBoard(data){
    return function(dispatch){
        return axios.post(`${API_URL}/boards`,
            {
                name: data.name
            }
        )
        .then(response => {
            if(response.status === 201){
                const result = response.data.result;
                dispatch({ type: ADD_BOARD_SUCCESS, data: result });
                return result;
            }
        });
    }
}

然后在你的组件中你可以这样做:

addBoard(formProps) {

    this.props.addBoard(formProps).then((result) => {
        console.log("Success!", result);
    })
    .catch(error => {
        console.error(error);
    });
}

如果你想在错误上发送catch,你可能也应该在你的行动中处理ADD_BOARD_FAIL,但是如果你还想要,那么你必须重新抛出那个错误在组件中捕获它。