根据文档,“没有中间件,Redux商店只支持同步数据流”。我不明白为什么会这样。为什么容器组件不能调用异步API,然后分派操作?

例如,想象一个简单的UI:一个字段和一个按钮。当用户按下按钮时,该字段将填充来自远程服务器的数据。

import * as React from 'react';
import * as Redux from 'redux';
import { Provider, connect } from 'react-redux';

const ActionTypes = {
    STARTED_UPDATING: 'STARTED_UPDATING',
    UPDATED: 'UPDATED'
};

class AsyncApi {
    static getFieldValue() {
        const promise = new Promise((resolve) => {
            setTimeout(() => {
                resolve(Math.floor(Math.random() * 100));
            }, 1000);
        });
        return promise;
    }
}

class App extends React.Component {
    render() {
        return (
            <div>
                <input value={this.props.field}/>
                <button disabled={this.props.isWaiting} onClick={this.props.update}>Fetch</button>
                {this.props.isWaiting && <div>Waiting...</div>}
            </div>
        );
    }
}
App.propTypes = {
    dispatch: React.PropTypes.func,
    field: React.PropTypes.any,
    isWaiting: React.PropTypes.bool
};

const reducer = (state = { field: 'No data', isWaiting: false }, action) => {
    switch (action.type) {
        case ActionTypes.STARTED_UPDATING:
            return { ...state, isWaiting: true };
        case ActionTypes.UPDATED:
            return { ...state, isWaiting: false, field: action.payload };
        default:
            return state;
    }
};
const store = Redux.createStore(reducer);
const ConnectedApp = connect(
    (state) => {
        return { ...state };
    },
    (dispatch) => {
        return {
            update: () => {
                dispatch({
                    type: ActionTypes.STARTED_UPDATING
                });
                AsyncApi.getFieldValue()
                    .then(result => dispatch({
                        type: ActionTypes.UPDATED,
                        payload: result
                    }));
            }
        };
    })(App);
export default class extends React.Component {
    render() {
        return <Provider store={store}><ConnectedApp/></Provider>;
    }
}

渲染导出的组件时,我可以单击该按钮,输入将正确更新。

注意connect调用中的update函数。它发送一个动作,告诉应用程序它正在更新,然后执行一个异步调用。调用完成后,所提供的值将作为另一个操作的有效负载进行调度。

这种方法有什么问题?为什么我要使用Redux Thunk或Redux Promise,如文档所示?

编辑:我在Redux repo中搜索线索,发现Action Creator在过去被要求是纯函数。例如,这里有一个用户试图为异步数据流提供更好的解释:

动作创建者本身仍然是一个纯函数,但它返回的thunk函数不需要是纯函数,它可以执行我们的异步调用

动作创作者不再需要纯粹。因此,thunk/promise中间件在过去肯定是必需的,但现在似乎不再是这样了?


当前回答

使用Redux saga是React Redux实现中最好的中间件。

前任:商店.js

  import createSagaMiddleware from 'redux-saga';
  import { createStore, applyMiddleware } from 'redux';
  import allReducer from '../reducer/allReducer';
  import rootSaga from '../saga';

  const sagaMiddleware = createSagaMiddleware();
  const store = createStore(
     allReducer,
     applyMiddleware(sagaMiddleware)
   )

   sagaMiddleware.run(rootSaga);

 export default store;

然后saga.js

import {takeLatest,delay} from 'redux-saga';
import {call, put, take, select} from 'redux-saga/effects';
import { push } from 'react-router-redux';
import data from './data.json';

export function* updateLesson(){
   try{
       yield put({type:'INITIAL_DATA',payload:data}) // initial data from json
       yield* takeLatest('UPDATE_DETAIL',updateDetail) // listen to your action.js 
   }
   catch(e){
      console.log("error",e)
     }
  }

export function* updateDetail(action) {
  try{
       //To write store update details
   }  
    catch(e){
       console.log("error",e)
    } 
 }

export default function* rootSaga(){
    yield [
        updateLesson()
       ]
    }

然后是action.js

 export default function updateFruit(props,fruit) {
    return (
       {
         type:"UPDATE_DETAIL",
         payload:fruit,
         props:props
       }
     )
  }

然后reducer.js

import {combineReducers} from 'redux';

const fetchInitialData = (state=[],action) => {
    switch(action.type){
      case "INITIAL_DATA":
          return ({type:action.type, payload:action.payload});
          break;
      }
     return state;
  }
 const updateDetailsData = (state=[],action) => {
    switch(action.type){
      case "INITIAL_DATA":
          return ({type:action.type, payload:action.payload});
          break;
      }
     return state;
  }
const allReducers =combineReducers({
   data:fetchInitialData,
   updateDetailsData
 })
export default allReducers; 

然后是main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/components/App.jsx';
import {Provider} from 'react-redux';
import store from './app/store';
import createRoutes from './app/routes';

const initialState = {};
const store = configureStore(initialState, browserHistory);

ReactDOM.render(
       <Provider store={store}>
          <App />  /*is your Component*/
       </Provider>, 
document.getElementById('app'));

试试这个。。正在工作

其他回答

这种方法有什么问题?为什么我要使用Redux Thunk或Redux Promise,如文档所示?

这种方法没有错。在大型应用程序中,这是不方便的,因为您将有不同的组件执行相同的操作,您可能希望取消某些操作,或保持某些本地状态,如自动递增ID靠近操作创建者等。因此,从维护的角度来看,将操作创建者提取到单独的函数中更容易。

您可以阅读我对“如何在超时情况下调度Redux操作”的回答,以了解更详细的演练。

像Redux Thunk或Redux Promise这样的中间件只是为你提供了发送Thunk或Promise的“语法糖”,但你不必使用它。

因此,如果没有任何中间件,您的动作创建者可能看起来像

// action creator
function loadData(dispatch, userId) { // needs to dispatch, so it is first argument
  return fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_DATA_FAILURE', err })
    );
}

// component
componentWillMount() {
  loadData(this.props.dispatch, this.props.userId); // don't forget to pass dispatch
}

但使用Thunk中间件,您可以这样写:

// action creator
function loadData(userId) {
  return dispatch => fetch(`http://data.com/${userId}`) // Redux Thunk handles these
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_DATA_FAILURE', err })
    );
}

// component
componentWillMount() {
  this.props.dispatch(loadData(this.props.userId)); // dispatch like you usually do
}

所以没有什么大的区别。我喜欢后一种方法的一点是,组件不关心动作创建者是异步的。它只是正常调用dispatch,它还可以使用mapDispatchToProps以短语法等方式绑定此类动作创建者。组件不知道动作创建者是如何实现的,您可以在不同的异步方法(Redux Thunk、Redux Promise、Redux Saga)之间切换,而无需更改组件。另一方面,使用前一种显式方法,您的组件确切地知道特定调用是异步的,并且需要通过某种约定(例如,作为同步参数)传递分派。

还请考虑此代码将如何更改。假设我们希望有第二个数据加载函数,并将它们组合在一个动作创建器中。

对于第一种方法,我们需要注意我们所称的行动创造者:

// action creators
function loadSomeData(dispatch, userId) {
  return fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}
function loadOtherData(dispatch, userId) {
  return fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_OTHER_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_OTHER_DATA_FAILURE', err })
    );
}
function loadAllData(dispatch, userId) {
  return Promise.all(
    loadSomeData(dispatch, userId), // pass dispatch first: it's async
    loadOtherData(dispatch, userId) // pass dispatch first: it's async
  );
}


// component
componentWillMount() {
  loadAllData(this.props.dispatch, this.props.userId); // pass dispatch first
}

使用Redux Thunk,动作创建者可以调度其他动作创建者的结果,甚至不考虑这些结果是同步的还是异步的:

// action creators
function loadSomeData(userId) {
  return dispatch => fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}
function loadOtherData(userId) {
  return dispatch => fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_OTHER_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_OTHER_DATA_FAILURE', err })
    );
}
function loadAllData(userId) {
  return dispatch => Promise.all(
    dispatch(loadSomeData(userId)), // just dispatch normally!
    dispatch(loadOtherData(userId)) // just dispatch normally!
  );
}


// component
componentWillMount() {
  this.props.dispatch(loadAllData(this.props.userId)); // just dispatch normally!
}

使用这种方法,如果您希望动作创建者查看当前的Redux状态,您可以只使用传递给thunks的第二个getState参数,而不必修改调用代码:

function loadSomeData(userId) {
  // Thanks to Redux Thunk I can use getState() here without changing callers
  return (dispatch, getState) => {
    if (getState().data[userId].isLoaded) {
      return Promise.resolve();
    }

    fetch(`http://data.com/${userId}`)
      .then(res => res.json())
      .then(
        data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
        err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
      );
  }
}

如果需要将其更改为同步,也可以在不更改任何调用代码的情况下执行此操作:

// I can change it to be a regular action creator without touching callers
function loadSomeData(userId) {
  return {
    type: 'LOAD_SOME_DATA_SUCCESS',
    data: localStorage.getItem('my-data')
  }
}

因此,使用Redux Thunk或Redux Promise等中间件的好处是,组件不知道动作创建者是如何实现的,也不知道它们是否关心Redux状态,它们是同步还是异步,以及它们是否调用其他动作创建者。缺点是有点间接,但我们认为这在实际应用中是值得的。

最后,Redux Thunk和朋友只是Redux应用程序中异步请求的一种可能方法。另一种有趣的方法是Redux Saga,它允许您定义长时间运行的守护进程(“sagas”),这些守护进程在执行操作时执行操作,并在输出操作之前转换或执行请求。这将逻辑从动作创作者转变为传奇。你可能想看看,然后选择最适合你的。

我在Redux repo中搜索线索,发现Action Creator在过去被要求是纯函数。

这是不正确的。医生们这么说,但医生们错了。动作创建者从未被要求是纯函数。我们修改了文档以反映这一点。

使用Redux saga是React Redux实现中最好的中间件。

前任:商店.js

  import createSagaMiddleware from 'redux-saga';
  import { createStore, applyMiddleware } from 'redux';
  import allReducer from '../reducer/allReducer';
  import rootSaga from '../saga';

  const sagaMiddleware = createSagaMiddleware();
  const store = createStore(
     allReducer,
     applyMiddleware(sagaMiddleware)
   )

   sagaMiddleware.run(rootSaga);

 export default store;

然后saga.js

import {takeLatest,delay} from 'redux-saga';
import {call, put, take, select} from 'redux-saga/effects';
import { push } from 'react-router-redux';
import data from './data.json';

export function* updateLesson(){
   try{
       yield put({type:'INITIAL_DATA',payload:data}) // initial data from json
       yield* takeLatest('UPDATE_DETAIL',updateDetail) // listen to your action.js 
   }
   catch(e){
      console.log("error",e)
     }
  }

export function* updateDetail(action) {
  try{
       //To write store update details
   }  
    catch(e){
       console.log("error",e)
    } 
 }

export default function* rootSaga(){
    yield [
        updateLesson()
       ]
    }

然后是action.js

 export default function updateFruit(props,fruit) {
    return (
       {
         type:"UPDATE_DETAIL",
         payload:fruit,
         props:props
       }
     )
  }

然后reducer.js

import {combineReducers} from 'redux';

const fetchInitialData = (state=[],action) => {
    switch(action.type){
      case "INITIAL_DATA":
          return ({type:action.type, payload:action.payload});
          break;
      }
     return state;
  }
 const updateDetailsData = (state=[],action) => {
    switch(action.type){
      case "INITIAL_DATA":
          return ({type:action.type, payload:action.payload});
          break;
      }
     return state;
  }
const allReducers =combineReducers({
   data:fetchInitialData,
   updateDetailsData
 })
export default allReducers; 

然后是main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/components/App.jsx';
import {Provider} from 'react-redux';
import store from './app/store';
import createRoutes from './app/routes';

const initialState = {};
const store = configureStore(initialState, browserHistory);

ReactDOM.render(
       <Provider store={store}>
          <App />  /*is your Component*/
       </Provider>, 
document.getElementById('app'));

试试这个。。正在工作

回答问题:

为什么容器组件不能调用异步API,然后调度行动?

我认为至少有两个原因:

第一个原因是关注点分离,调用api并获取数据不是动作创建者的工作,您必须向动作创建者函数传递两个参数,即动作类型和有效载荷。

第二个原因是因为redux存储正在等待一个具有强制操作类型和可选有效负载的普通对象(但这里也必须传递有效负载)。

动作创建者应该是一个简单的对象,如下所示:

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

Redux Thunk middleware的任务是将api调用的结果显示给适当的操作。

我认为至少有两个原因:

第一个原因是关注点分离,调用api并获取数据不是动作创建者的工作,您必须向动作创建者函数传递两个参数,即动作类型和有效载荷。

第二个原因是因为redux存储正在等待一个具有强制操作类型和可选有效负载的普通对象(但这里也必须传递有效负载)。

动作创建者应该是一个简单的对象,如下所示:

函数addTodo(文本){返回{类型:ADD_TODO,文本}}Redux Thunk middleware的任务是将api调用的结果显示给适当的操作。

要回答开头提出的问题:

为什么容器组件不能调用异步API,然后分派操作?

请记住,这些文档适用于Redux,而不是Redux+React。连接到React组件的Redux商店可以做到您所说的一切,但没有中间件的Plain Jane Redux商店不接受除普通对象之外的参数来分派。

如果没有中间件,你当然还可以

const store = createStore(reducer);
MyAPI.doThing().then(resp => store.dispatch(...));

但这是一个类似的情况,异步是围绕着Redux而不是由Redux处理的。因此,中间件通过修改可以直接传递给调度的内容来允许异步。


也就是说,我认为你的建议的精神是有效的。在Redux+Rreact应用程序中,当然还有其他方法可以处理异步。

使用中间件的一个好处是,您可以继续正常使用动作创建者,而不必担心它们是如何连接的。例如,使用redux thunk,您编写的代码看起来很像

function updateThing() {
  return dispatch => {
    dispatch({
      type: ActionTypes.STARTED_UPDATING
    });
    AsyncApi.getFieldValue()
      .then(result => dispatch({
        type: ActionTypes.UPDATED,
        payload: result
      }));
  }
}

const ConnectedApp = connect(
  (state) => { ...state },
  { update: updateThing }
)(App);

它看起来与原始版本没有太大区别-只是有点混乱-connect不知道updateThing是(或需要)异步的。

如果您还想支持承诺、可观测性、传奇或疯狂的自定义和高度声明性的动作创建者,那么Redux可以通过更改传递给分派的内容(也就是从动作创建者返回的内容)来实现。无需干扰React组件(或连接调用)。