为组件提供thunk动作的惯用方法?

时间:2016-12-09 09:19:25

标签: react-redux redux-thunk

我编写了以下thunk动作创建器,用于向api发出请求。

如果我的理解是正确的,thunk action creator将由中间件处理,并且可以访问商店调度方法。

使这个thunk action creator可用于react组件的惯用方法是什么?

我能想到的最好的方法就是直接导入thunk action creator。

export function fetchMovie(title) { 

    return (dispatch) => {

        dispatch(requestMovie(title));
        const url = `http://www.omdbapi.com/?t=${title}&y=&plot=short&r=json`

        return axios.get(url)
                    .then(response => {
                        dispatch(receiveMovie(title, response.data))
                    })
                   .catch(err => dispatch(requestMovieErr(title,   err)))
        }
}

1 个答案:

答案 0 :(得分:0)

是的,你的假设是正确的。最常见的方法是根据需要将单个操作函数导入到组件中,例如:

import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
// step 1: import action 'fetchMovie'
import { fetchMovie } from './actions/whateverYourFileIsCalled';

class SomeComponent extends Component {

    render() {

        return (
            <div>
                {/* 
                  step 3: use the 'fetchMovie' action
                  that is now part of the component's props 
                  wherever we'd like
                */}
                <button onClick={this.props.fetchMovie.bind(null, 'Jurassic Park')}>
                    Click here for dinosaurs
                </button>
            </div>
        );
    }
}

SomeComponent.propTypes = {
    fetchMovie: PropTypes.func.isRequired
};

export default connect(
    {},
    {
        // step 2:
        // connect the 'fetchMovie' action to this component's props using redux helper
        fetchMovie
    }
)(SomeComponent);