拦截redux中的异步操作

时间:2017-03-20 08:56:24

标签: redux react-redux

我正在使用与redux的反应构建一个简单的笔记应用程序。我的创建笔记操作如下所示:

import axios from "axios";

const URL = 'http://localhost:3002/api/';

export function createNote(data = {}) {
    return {
        type: 'CREATE_NOTE',
        payload: axios.post(URL + 'notes/', data),
    };
}

我的减速机中有以下内容:

    // Create
    case 'CREATE_NOTE_PENDING':
    {
        return {
            ...state,
            creating: true
        };
    }

    case 'CREATE_NOTE_FULFILLED':
    {
        return {
            ...state,
            creating: false,
            notes: action.payload.data
        };
    }

    case 'CREATE_NOTE_REJECTED': {
        return {
            ...state,
            creating: false,
            error: action.payload
        };
    }

这是我的Notes课程:

function mapStateToProps(store) {
    return {
        data: store.note.notes,
        fetching: store.note.fetching,
        creating: store.note.creating,
        error: store.note.error,
    };
}

class Notes extends Component {

    componentWillMount() {
        this.props.dispatch(fetchNotes());
    }

    create() {
        this.props.dispatch(createNote({
            title: this.refs.title.value,
            content: this.refs.content.value,
        }));

        this.refs.title.value = '';
        this.refs.content.value = '';
    }

    render() {
        return (
            <div className="App">
                <h1 className="text-center">Notepad</h1>
                <div className="row">

                    <div className="col-md-6 col-md-offset-3">
                        <div className="form-group">
                            <input ref="title" placeholder="Create a note" className="form-control" disabled={this.props.creating} />
                        </div>
                        <div className="form-group">
                            <textarea ref="content" className="form-control" disabled={this.props.creating} />
                        </div>
                        <button onClick={this.create.bind(this)}
                                type="submit"
                                className="btn btn-primary"
                                style={{float: 'right'}}
                                disabled={this.props.creating} >Save</button>
                    </div>

                </div>

否创建我将禁用表单,直到我从服务器获得答案并重置表单内的内容。我的问题是当我得到回复时如何重置表单内容,即表单何时启用?

1 个答案:

答案 0 :(得分:1)

如果要控制输入和文本区域的内容,则应使用受控组件。那就是提供一个值属性,例如,输入

<input value={this.state.title} placeholder="Create a note" className="form-control" disabled={this.props.creating} />

您可以使用内部状态或redux状态作为值。然后,您可以通过setState或redux操作控制该值。