2017-03-20 4 views
0

Ich baue eine einfache Notizen App mit Reaktion mit Redux. Meine Notizen erstellen sieht Aktion wie folgt aus:Abfangen einer asynchronen Aktion in 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), 
    }; 
} 

Und ich habe folgendes in meinem Minderer:

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

Und das ist meine Notizen Klasse:

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> 

Nein erstellen Ich werde das Formular deaktivieren, bis ich eine Antwort vom Server bekomme und den Inhalt im Formular zurücksetze. Meine Frage ist wie man den Inhalt des Formulars zurücksetzt, wenn ich Antwort habe, d. H. Wann das Formular aktiviert ist?

Antwort

1

Wenn Sie den Inhalt von Eingabe- und Textbereich steuern möchten, sollten Sie kontrollierte Komponenten verwenden. Das bedeutet, ein Wertattribut z. Eingabe

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

Sie können entweder internen Status oder Redux-Status für den Wert verwenden. Dann können Sie den Wert durch setState- oder Redux-Aktionen steuern.

+0

Ihre Antwort war sehr hilfreich! Vielen Dank! –

Verwandte Themen