redux-thunk使用_Redux Thunk用示例解释

redux-thunk使用

Redux Thunk is middleware that allows you to return functions, rather than just actions, within Redux. This allows for delayed actions, including working with promises.

Redux Thunk是一种中间件,可让您在Redux中返回函数,而不只是操作。 这允许延迟的行动,包括履行承诺。

One of the main use cases for this middleware is for handling actions that might not be synchronous, for example, using axios to send a GET request. Redux Thunk allows us to dispatch those actions asynchronously and resolve each promise that gets returned.

该中间件的主要用例之一是处理可能不同步的动作,例如,使用axios发送GET请求。 Redux Thunk允许我们异步调度这些动作并解决每个返回的诺言。

安装与设定 (Installation and Setup)

Redux Thunk can be installed by running npm install redux-thunk --save or yarn add redux-thunk in the command line.

可以通过在命令行中运行npm install redux-thunk --saveyarn add redux-thunk来安装Redux Thunk。

Because it is a Redux tool, you will also need to have Redux set up. Once installed, it is enabled using applyMiddleware():

因为它是Redux工具,所以您还需要设置Redux。 安装后,可使用applyMiddleware()启用它:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

如何使用Redux Thunk (How to Use Redux Thunk)

Once Redux Thunk has been installed and included in your project with applyMiddleware(thunk), you can start dispatching actions asynchronously.

一旦安装了Redux Thunk并通过applyMiddleware(thunk)将其包含在您的项目中,就可以开始异步调度动作。

For example, here's a simple increment counter:

例如,这是一个简单的增量计数器:

const INCREMENT_COUNTER = 'INCREMENT_COUNTER';

function increment() {
  return {
    type: INCREMENT_COUNTER
  };
}

function incrementAsync() {
  return dispatch => {
    setTimeout(() => {
      // You can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}

And here's how set up success and failure actions after polling an API:

以下是轮询API后如何设置成功和失败操作:

const GET_CURRENT_USER = 'GET_CURRENT_USER';
const GET_CURRENT_USER_SUCCESS = 'GET_CURRENT_USER_SUCCESS';
const GET_CURRENT_USER_FAILURE = 'GET_CURRENT_USER_FAILURE';

const getUser = () => {
  return (dispatch) => {     //nameless functions
    // Initial action dispatched
    dispatch({ type: GET_CURRENT_USER });
    // Return promise with success and failure actions
    return axios.get('/api/auth/user').then(  
      user => dispatch({ type: GET_CURRENT_USER_SUCCESS, user }),
      err => dispatch({ type: GET_CURRENT_USER_FAILURE, err })
    );
  };
};

更多信息: (More Information:)

翻译自: https://www.freecodecamp.org/news/redux-thunk-explained-with-examples/

redux-thunk使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值