When would bindActionCreators be used in react/redux?

后端 未结 10 1077
温柔的废话
温柔的废话 2020-12-07 11:04

Redux docs for bindActionCreators states that:

The only use case for bindActionCreators is when you want to pass some action cre

10条回答
  •  情话喂你
    2020-12-07 11:49

    One nice use case for bindActionCreators is for integration with redux-saga using redux-saga-routines. For example:

    // routines.js
    import { createRoutine } from "redux-saga-routines";
    export const fetchPosts = createRoutine("FETCH_POSTS");
    
    // Posts.js
    import React from "react";
    import { bindActionCreators } from "redux";
    import { connect } from "react-redux";
    import { fetchPosts } from "routines";
    
    class Posts extends React.Component {
      componentDidMount() {
        const { fetchPosts } = this.props;
        fetchPosts();
      }
    
      render() {
        const { posts } = this.props;
        return (
          
      {posts.map((post, i) => (
    • {post}
    • ))}
    ); } } const mapStateToProps = ({ posts }) => ({ posts }); const mapDispatchToProps = dispatch => ({ ...bindActionCreators({ fetchPosts }, dispatch) }); export default connect( mapStateToProps, mapDispatchToProps )(Posts);
    // reducers.js
    import { fetchPosts } from "routines";
    
    const initialState = [];
    
    export const posts = (state = initialState, { type, payload }) => {
      switch (type) {
        case fetchPosts.SUCCESS:
          return payload.data;
        default:
          return state;
      }
    };
    
    // api.js
    import axios from "axios";
    
    export const JSON_OPTS = { headers: { Accept: "application/json" } };
    export const GET = (url, opts) =>
      axios.get(url, opts).then(({ data, headers }) => ({ data, headers }));
    
    // sagas.js
    import { GET, JSON_OPTS } from "api";
    import { fetchPosts } from "routines";
    import { call, put, takeLatest } from "redux-saga/effects";
    
    export function* fetchPostsSaga() {
      try {
        yield put(fetchPosts.request());
        const { data } = yield call(GET, "/api/posts", JSON_OPTS);
        yield put(fetchPosts.success(data));
      } catch (error) {
        if (error.response) {
          const { status, data } = error.response;
          yield put(fetchPosts.failure({ status, data }));
        } else {
          yield put(fetchPosts.failure(error.message));
        }
      } finally {
        yield put(fetchPosts.fulfill());
      }
    }
    
    export function* fetchPostsRequestSaga() {
      yield takeLatest(fetchPosts.TRIGGER, fetchPostsSaga);
    }
    

    Note that this pattern could be implemented using React Hooks (as of React 16.8).

提交回复
热议问题