Ich verwende ReactJS + Redux zusammen mit Express und Webpack. Es ist eine API aufgebaut, und ich möchte in der Lage sein, REST -Aufrufe - GET, POST, PUT, DELETE - vom Client aus auszuführen.
Wie und was ist der richtige Weg, dies mit der Redux-Architektur zu tun? Jedes gute Beispiel für den Fluss in Bezug auf Reduzierungen, Aktionsersteller, Speicher- und Reaktionswege wäre äußerst hilfreich.
Danke im Voraus!
Am einfachsten geht es mit redux-thunk
package. Dieses Paket ist eine Redux-Middleware, also sollten Sie es zuerst mit Redux verbinden:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
Auf diese Weise können Sie async
-Aktionen zusammen mit regulären sync
-Aktionen auslösen. Lassen Sie uns eine davon erstellen:
// actions.js
export function fetchTodos() {
// Instead of plain objects, we are returning function.
return function(dispatch) {
// Dispatching REQUEST action, which tells our app, that we are started requesting todos.
dispatch({
type: 'FETCH_TODOS_REQUEST'
});
return fetch('/api/todos')
// Here, we are getting json body(in our case it will contain `todos` or `error` prop, depending on request was failed or not) from server response
// And providing `response` and `body` variables to the next chain.
.then(response => response.json().then(body => ({ response, body })))
.then(({ response, body }) => {
if (!response.ok) {
// If request was failed, dispatching FAILURE action.
dispatch({
type: 'FETCH_TODOS_FAILURE',
error: body.error
});
} else {
// When everything is ok, dispatching SUCCESS action.
dispatch({
type: 'FETCH_TODOS_SUCCESS',
todos: body.todos
});
}
});
}
}
Ich bevorzuge es, die Reaktionskomponenten auf Präsentations- und Behälterkomponenten zu trennen. Dieser Ansatz wurde in diesem Artikel perfekt beschrieben.
Als Nächstes sollten wir eine TodosContainer
-Komponente erstellen, die der präsentativen Todos
-Komponente Daten liefert. Hier verwenden wir die react-redux
-Bibliothek:
// TodosContainer.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchTodos } from '../actions';
class TodosContainer extends Component {
componentDidMount() {
// When container was mounted, we need to start fetching todos.
this.props.fetchTodos();
}
render() {
// In some simple cases, it is not necessary to create separate `Todos` component. You can put todos markup directly here.
return <Todos items={this.props.todos} />
}
}
// This function is used to convert redux global state to desired props.
function mapStateToProps(state) {
// `state` variable contains whole redux state.
return {
// I assume, you have `todos` state variable.
// Todos will be available in container component as `this.props.todos`
todos: state.todos
};
}
// This function is used to provide callbacks to container component.
function mapDispatchToProps(dispatch) {
return {
// This function will be available in component as `this.props.fetchTodos`
fetchTodos: function() {
dispatch(fetchTodos());
}
};
}
// We are using `connect` function to wrap our component with special component, which will provide to container all needed data.
export default connect(mapStateToProps, mapDispatchToProps)(TodosContainer);
Sie sollten auch todosReducer
erstellen, die die FETCH_TODOS_SUCCESS
-Aktion behandelt, und weitere 2 Aktionen, wenn Sie den Loader/die Fehlermeldung anzeigen möchten.
// reducers.js
import { combineReducers } from 'redux';
const INITIAL_STATE = {
items: [],
isFetching: false,
error: undefined
};
function todosReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case 'FETCH_TODOS_REQUEST':
// This time, you may want to display loader in the UI.
return Object.assign({}, state, {
isFetching: true
});
case 'FETCH_TODOS_SUCCESS':
// Adding derived todos to state
return Object.assign({}, state, {
isFetching: false,
todos: action.todos
});
case 'FETCH_TODOS_FAILURE':
// Providing error message to state, to be able display it in UI.
return Object.assign({}, state, {
isFetching: false,
error: action.error
});
default:
return state;
}
}
export default combineReducers({
todos: todosReducer
});
Für andere Operationen wie CREATE
, UPDATE
, DELETE
gibt es nichts Besonderes, sie implementieren auf dieselbe Weise.
Die kurze Antwort lautet:
redux-thunk
und redux-saga
, wie andere bereits gesagt haben.Für eine einfache, einfache Bibliothek, die Sie in Ihre Redux-App aufnehmen können, können Sie redux-crud-store versuchen. Haftungsausschluss: Ich habe es geschrieben. Sie können auch die Quelle für redux-crud-store lesen, wenn Sie daran interessiert sind, die Abruf-API oder einen anderen API-Client mit redux-saga zu integrieren
Dies ist der primäre Anwendungsfall für Bibliotheken wie redux-thunk
, redux-saga
und redux-observable
.
redux-thunk
ist der einfachste, bei dem Sie Folgendes tun würden:
import fetch from 'isomorphic-fetch'
export const REQUEST_POSTS = 'REQUEST_POSTS'
function requestPosts(subreddit) {
return {
type: REQUEST_POSTS,
subreddit
}
}
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
function receivePosts(subreddit, json) {
return {
type: RECEIVE_POSTS,
subreddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
}
}
// Meet our first thunk action creator!
// Though its insides are different, you would use it just like any other action creator:
// store.dispatch(fetchPosts('reactjs'))
export function fetchPosts(subreddit) {
// Thunk middleware knows how to handle functions.
// It passes the dispatch method as an argument to the function,
// thus making it able to dispatch actions itself.
return function (dispatch) {
// First dispatch: the app state is updated to inform
// that the API call is starting.
dispatch(requestPosts(subreddit))
// The function called by the thunk middleware can return a value,
// that is passed on as the return value of the dispatch method.
// In this case, we return a promise to wait for.
// This is not required by thunk middleware, but it is convenient for us.
return fetch(`http://www.reddit.com/r/${subreddit}.json`)
.then(response => response.json())
.then(json =>
// We can dispatch many times!
// Here, we update the app state with the results of the API call.
dispatch(receivePosts(subreddit, json))
)
// In a real world app, you also want to
// catch any error in the network call.
}
}
Das obige Beispiel stammt direkt aus http://redux.js.org/docs/advanced/AsyncActions.html , das wirklich die endgültige Quelle für Antworten auf Ihre Frage ist.