2017-12-21 47 views
0

서버 측 렌더링 (SSR)이 redux-api과 작동하도록 고민 중입니다. 이 응용 프로그램은 클라이언트 측 렌더링 (CSR)으로 잘 작동합니다.Next.js 및 redux-api가 작동하는 방법 (next-redux-wrapper 사용)

SSR이 작동하려면 Next.js의 getInitialProps 기능에서 데이터를 사용할 수 있어야합니다. 나는 next-redux-wrapper을 사용하여 함께 묶으려고합니다.

현재 상태 :

class ShowLessonPage extends React.Component { 

    static async getInitialProps ({store, isServer, pathname, query}) { 
     console.log(`getInitialProps`, {store, isServer, pathname, query}); 
     const { dispatch } = store; 
     const lessonSlug = query.lessonSlug; 
     // Get one Lesson 
     dispatch(reduxApi.actions.oneLesson({ id: `slug=${lessonSlug}` })); 
    } 

    render() { 
     console.log('render', this.props.oneLesson); 
     const lesson = this.props.oneLesson.data; 
     //... 
    } 

    //..... 

} 

const createStoreWithThunkMiddleware = applyMiddleware(thunk)(createStore); 
const reducer = combineReducers(myReduxApi.reducers); // redux-api 

const makeStore = function (state, enhancer) { 
    return createStoreWithThunkMiddleware(reducer, state); 
} 

const mapStateToProps = function (state) { 
    return { oneLesson: state.oneLesson }; 
}; 

// withRedux = next-redux-wrapper 
const ShowLessonPageConnected = withRedux({ createStore: makeStore, mapStateToProps: mapStateToProps })(ShowLessonPage) 
export default ShowLessonPageConnected; 

나는 적어도 지금 getInitialPropsstore를 얻을,하지만 난 내 CSR의 앱 (사전 withRedux) 버전이 없었다 이상한 Error: only absolute urls are supported 메시지가 표시됩니다. 그리고 this.props.oneLesson.data은 물론 비어 있습니다.

makeStore이 서버 생성 호출에서 state = undefined이되고 있습니다. 아마 단서가됩니다.

redux-api도 비슷한 방식으로 바꿉니다.

업데이트 1 : 모든 URL을 가득 채워서 Redux가 이제 내 API 엔드 포인트를 때리고 있습니다. 콘솔 출력을 참조하지만 한 페이지를 다시로드 것이 makeStore만큼이나 3 배 이하를 호출하고 첫 번째 호출은 올바른 슬러그를 포함

makeStore { state: undefined, reqParams: { lessonSlug: 'tyrannosaurus-rex' } } 
getInitialProps { query: { lessonSlug: 'tyrannosaurus-rex' } } 
API: GET request: { _id: 'slug=tyrannosaurus-rex' } 
makeStore { state: undefined, reqParams: { lessonSlug: 'undefined' } } 
getInitialProps { query: { lessonSlug: 'undefined' } } 
API: GET request: { _id: 'slug=undefined' } 
makeStore { state: undefined, reqParams: { lessonSlug: 'undefined' } } 
getInitialProps { query: { lessonSlug: 'undefined' } } 
API: GET request: { _id: 'slug=undefined' } 

업데이트를 2 : 획기적인 : getInitialProps 차종에서 약속을 반환 SSR 작업. 이제 클라이언트 측 렌더링이 충분히 재미 있습니다.

static async getInitialProps ({store, isServer, pathname, query}) { 
    const { dispatch } = store; 
    const lessonSlug = query.lessonSlug; 
    const resultPromise = await dispatch(reduxApi.actions.oneLesson({ id: `slug=${lessonSlug}` })); 
    return resultPromise; 
} 

답변

0

나는 하루 종일 머리카락을 당긴 후 그것을 해결할 수있었습니다.

  1. 절대 URL : 그것은 예상대로 일을하기 전에

    는 많은 문제가 있었다. 클라이언트 전용 코드는 상대 URL에는 문제가 없었지만 서버는이를 수행했습니다.

  2. getInitialProps은 결과에 대한 약속을 반환해야합니다 (아래 참조).
  3. 내 데이터 개체 (oneLesson)가 this.state이 아니고, 예상 한대로 this.props이 아니 었습니다 (서버 및 클라이언트에서 렌더링 할 수있는 한 실제로 사용하지 않았습니다). 여기

    static async getInitialProps ({store, isServer, pathname, query}) { 
        const { dispatch } = store; 
        const lessonSlug = query.lessonSlug; 
        const resultPromise = await dispatch(reduxApi.actions.oneLesson({ id: `slug=${lessonSlug}` })); 
        return resultPromise; 
    } 
    

    Next.js, REDUX-API의 완전한 작동 예를, 그리고 다음-REDUX - 래퍼 조화 작업 :

여기 getInitialProps의 최종 버전입니다

https://github.com/tomsoderlund/nextjs-express-mongoose-crudify-boilerplate