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 --save
或yarn 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使用