【问题标题】:How to dispatch multiple action creators (React + Redux + Server-side rendering)如何调度多个动作创建者(React + Redux + 服务端渲染)
【发布时间】:2018-09-08 15:22:48
【问题描述】:

我一直在学习如何使用 React 和 Redux 构建服务器端渲染应用程序的精彩课程,但我现在处于课程未涵盖的情况,我自己无法弄清楚.

请考虑以下组件(非常基本,除了底部的导出部分):

class HomePage extends React.Component {

    componentDidMount() {       
        this.props.fetchHomePageData();
    }   

    handleLoadMoreClick() {
        this.props.fetchNextHomePagePosts();
    }   

    render() {

        const posts = this.props.posts.homepagePosts; 
        const featuredProject = this.props.posts.featuredProject; 
        const featuredNews = this.props.posts.featuredNews; 
        const banner = this.props.posts.banner; 
        const data = ( posts && featuredProject && featuredNews && banner ); 

        if( data == undefined ) {
            return <Loading />; 
        }

        return(
            <div>
                <FeaturedProject featuredProject={ featuredProject } />
                <FeaturedNews featuredNews={ featuredNews } />
                <Banner banner={ banner } />                
                <PostsList posts={ posts } heading="Recently on FotoRoom" hasSelect={ true } />
                <LoadMoreBtn onClick={ this.handleLoadMoreClick.bind( this ) } />               
            </div>
        ); 

    }

}

function mapStateToProps( { posts } ) {
    return { posts }
}

export default {
    component: connect( mapStateToProps, { fetchHomePageData, fetchNextHomePagePosts } )( HomePage ),
    loadData: ( { dispatch } ) => dispatch( fetchHomePageData() )
};

上述工作正常:loadData 函数发出 API 请求以获取一些数据,这些数据通过 mapStateToProps 函数馈送到组件中。但是,如果我想在同一个 loadData 函数中触发多个动作创建者怎么办?唯一可行的方法是,如果我这样编写函数:

function loadData( store ) {
    store.dispatch( fetchFeaturedNews() );
    return store.dispatch( fetchHomePageData() );
}

export default {
    component: connect( mapStateToProps, { fetchHomePageData, fetchNextHomePagePosts } )( HomePage ),
    loadData: loadData
};

但这不是很好,因为我需要返回所有数据......请记住,导出的组件最终会出现在以下路由配置中:

const Routes = [
    {
        ...App, 
        routes: [
            {
                ...HomePage, // Here it is!
                path: '/', 
                exact: true
            },
            {
                ...LoginPage, 
                path: '/login'
            },              
            {
                ...SinglePostPage, 
                path: '/:slug'
            },
            {
                ...ArchivePage, 
                path: '/tag/:tag'
            },                                      
        ]
    }
];

下面是当某个路由需要组件时如何使用 loadData 函数:

app.get( '*', ( req, res ) => {

    const store = createStore( req ); 

    const fetchedAuthCookie = req.universalCookies.get( authCookie ); 

    const promises = matchRoutes( Routes, req.path ).map( ( { route } ) => {
        return route.loadData ? route.loadData( store, req.path, fetchedAuthCookie ) : null;
    }).map( promise => {
        if( promise ) {
            return new Promise( ( resolve, reject ) => {
                promise.then( resolve ).catch( resolve ); 
            }); 
        }
    });

    ...

}

另外,下面是动作创建者触发的动作示例。他们都返回承诺:

export const fetchHomePageData = () => async ( dispatch, getState, api ) => {

    const posts = await api.get( allPostsEP );

    dispatch({
        type: 'FETCH_POSTS_LIST', 
        payload: posts
    });             

}

和减速器:

export default ( state = {}, action ) => {
    switch( action.type ) {
        case 'FETCH_POSTS_LIST':
            return {
                ...state, 
                homepagePosts: action.payload.data 
            }                                       
        default: 
            return state; 
    }
}

【问题讨论】:

  • 我可能遗漏了一些东西,但你不能只返回数组吗?你能告诉你loadData 函数后来是如何使用的吗?
  • @TomaszMularczyk 嗨,我已经更新了我的答案。感谢收看!
  • @grazianodev 你能解释一下吗但这不是很好,因为我需要返回所有数据? “要返回的数据”是什么意思?
  • @MayankShukla 好吧,现在 loadData 函数只返回 fetchHomePageData() 获取的数据;我想要的是让 loadData 函数返回它和fetchFeaturedNews() 获取的数据。换句话说,我希望它返回两组数据而不仅仅是一组数据,以便它们都可以在我的问题最底部的app.get( ... ) 函数中映射。将它们组合成一个像@TomasMularczyk 建议的数组听起来不错,但我似乎无法让它工作......
  • Could show implementation of fetch... 他们返回 Promise 吗?

标签: javascript reactjs redux server-side-rendering


【解决方案1】:

因此,您的操作返回一个 Promise,而您在问如何返回多个 Promise。使用Promise.all:

function loadData({ dispatch }) {
  return Promise.all([
    dispatch( fetchFeaturedNews() ),
    dispatch( fetchHomePageData() ),
  ]);
}

但是...请记住,Promise.all 将在所有 Promise 解析时解析,并且它会返回一个 Array 值:

function loadData({ dispatch }) {
  return Promise.all([
    dispatch( fetchFeaturedNews() ),
    dispatch( fetchHomePageData() ),
  ]).then(listOfResults => {
    console.log(Array.isArray(listOfResults)); // "true"
    console.log(listOfResults.length); // 2
  });
}

所以你可能想以不同的方式处理它。

【讨论】:

  • 正是我想要的。非常感谢!
  • 谢谢。但是在 mapStatetoProps 函数中如何处理,我只得到第二个请求的结果。
猜你喜欢
  • 2016-03-26
  • 2016-04-03
  • 2017-08-13
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多