如何调度多个动作创建者(React + Redux + 服务端渲染)

gra*_*dev 5 javascript reactjs redux server-side-rendering

我一直在学习关于如何使用 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() )
};
Run Code Online (Sandbox Code Playgroud)

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

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

export default {
    component: connect( mapStateToProps, { fetchHomePageData, fetchNextHomePagePosts } )( HomePage ),
    loadData: loadData
};
Run Code Online (Sandbox Code Playgroud)

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

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

以下是一旦某个路由需要组件时如何使用 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 ); 
            }); 
        }
    });

    ...

}
Run Code Online (Sandbox Code Playgroud)

此外,这里是动作创建者触发的动作的示例。他们都回报承诺:

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

    const posts = await api.get( allPostsEP );

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

}
Run Code Online (Sandbox Code Playgroud)

和减速机:

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

Tom*_*zyk 2

因此,您的操作会返回一个 Promise,并且您会问如何返回多个 Promise。使用Promise.all

function loadData({ dispatch }) {
  return Promise.all([
    dispatch( fetchFeaturedNews() ),
    dispatch( fetchHomePageData() ),
  ]);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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