📜  redux-thunk - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:04:52.822000             🧑  作者: Mango

Redux-Thunk

Redux-Thunk是一个Redux的中间件,用于异步处理actions,可以让我们在actions中使用异步操作,比如发起网络请求等。

安装

可以使用npm或yarn安装:

npm install redux-thunk --save

yarn add redux-thunk
使用
  1. 在创建store的时候,在applyMiddleware中加入thunk中间件:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));
  1. 在actions中使用异步操作:
export const fetchTodos = () => {
  return (dispatch) => {
    dispatch(todosFetchStarted());

    fetch('https://api.example.com/todos')
      .then(response => response.json())
      .then(todos => dispatch(todosFetchSuccess(todos)))
      .catch(error => dispatch(todosFetchFailure(error)));
  };
};

上述代码中,fetchTodos函数返回的是一个函数,并且参数中传入了dispatch,这里就可以用dispatch触发action,比如最后的todosFetchSuccess。

总结

Redux-Thunk是一个非常好用的中间件,可以让我们在Redux中方便地处理异步操作,提高开发效率,降低出错几率。