Definitivamente persistono lo stato dei vostri riduttori!
Se hai persistito una sequenza di azioni, non saresti mai in grado di modificare le tue azioni nel frontend senza manipolare il database prod.
Esempio: persistere uno stato di riduttore a un server
Inizieremo con tre tipi di azione in più:
// actions: 'SAVE', 'SAVE_SUCCESS', 'SAVE_ERROR'
Io uso redux-thunk fare chiamate al server asincrona: significa che un'azione funzione creator può azioni aggiuntive dispatch
e ispezionare lo stato corrente.
Il creatore di azioni save
invia immediatamente un'azione (in modo che sia possibile mostrare una casella di selezione o disabilitare un pulsante "Salva" nell'interfaccia utente). Quindi invia le azioni SAVE_SUCCESS
o SAVE_ERROR
una volta completata la richiesta POST.
var actionCreators = {
save:() => {
return (dispatch, getState) => {
var currentState = getState();
var interestingBits = extractInterestingBitsFromState(currentState);
dispatch({type: 'SAVE'});
window.fetch(someUrl, {
method: 'POST',
body: JSON.stringify(interestingBits)
})
.then(checkStatus) // from https://github.com/github/fetch#handling-http-error-statuses
.then((response) => response.json())
.then((json) => dispatch actionCreators.saveSuccess(json.someResponseValue))
.catch((error) =>
console.error(error)
dispatch actionCreators.saveError(error)
);
}
},
saveSuccess: (someResponseValue) => return {type: 'SAVE_SUCCESS', someResponseValue},
saveError: (error) => return {type: 'SAVE_ERROR', error},
// other real actions here
};
(N.B. $.ajax
sarebbe totalmente lavorare al posto della roba window.fetch
, ho appena preferisco non caricare l'intera jQuery per una funzione!)
Il riduttore appena registra ogni richiesta del server in sospeso.
function reducer(state, action) {
switch (action.type) {
case 'SAVE':
return Object.assign {}, state, {savePending: true, saveSucceeded: null, saveError: null}
break;
case 'SAVE_SUCCESS':
return Object.assign {}, state, {savePending: false, saveSucceeded: true, saveError: false}
break;
case 'SAVE_ERROR':
return Object.assign {}, state, {savePending: false, saveSucceeded: false, saveError: true}
break;
// real actions handled here
}
}
Probabilmente si vorrà fare qualcosa con la someResponseValue
che è tornato dal server - forse è un id di un'entità di nuova creazione ecc ecc
Spero che questo aiuta, ha funzionato bene così lontano per me!
Penso che il backend di solito sia piuttosto classico (un normale DB), non diverso dalle altre app CRUD. Tuttavia potresti essere interessato ad approcci come https://www.rethinkdb.com e http://www.confluent.io/blog/turning-the-database-inside-out-with-apache-samza/. –