【问题标题】:Idiomatic way of making a thunk action available to components?使组件可以使用 thunk 操作的惯用方式?
【发布时间】:2017-04-24 17:25:10
【问题描述】:

我编写了以下 thunk action creator,用于向 api 发出请求。

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

让这个 thunk 动作创建器可用于 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)))
        }
}

【问题讨论】:

    标签: react-redux redux-thunk


    【解决方案1】:

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

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 2018-09-22
      • 2020-07-11
      • 2014-10-07
      • 2019-06-08
      相关资源
      最近更新 更多