最も簡単な方法は、redux-thunk
パッケージを使用することです。これはあなたが定期的にsync
アクションと一緒にasync
アクションを派遣することができます
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
:このパッケージにはとてもまず、あなたはReduxのにそれを接続する必要があり、Reduxのミドルウェアです。それらのうちの1つを作成しましょう:プレゼンテーションコンポーネントとコンテナコンポーネントの反応コンポーネントを分離することをお勧めします。このアプローチは、this articleに完全に記載されています。
次に、コンポーネントを作成して、プレゼンテーション用のTodos
コンポーネントにデータを提供する必要があります。あなたが表示ローダ/エラーメッセージをしたい場合はFETCH_TODOS_SUCCESS
アクションを処理します
// 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);
また、あなたがtodosReducer
を作成する必要があり、そして他の2つのアクション:ここでは、我々はreact-redux
ライブラリを使用しています。
// 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
});
CREATE
のような他の操作について
、UPDATE
、DELETE
何も特別なことは、彼らが同じように実装している、存在しません。
ありがとうございました。まだそのコンセプトを把握しようとしています。どのようにしてコンポーネントからアクションを呼び出すのですか?また、 '.then(response => response.json()。then(body =>({response、body}))))) .then(({response、body})=> {お返事を –
@JoKo、はい、すぐに回答を更新します。 – 1ven
@JoKo、更新された回答 – 1ven