【问题标题】:next-redux-wrapper Wrapper.getStaticProps not working withnext-redux-wrapper Wrapper.getStaticProps 无法使用
【发布时间】:2021-11-06 00:59:44
【问题描述】:

这是我的后端控制器,我正在获取房间数据

const allRooms = catchAsyncErrors(async (req, res) => {

    const resPerPage = 4;

    const roomsCount = await Room.countDocuments();

    const apiFeatures = new APIFeatures(Room.find(), req.query)
        .search()
        .filter()

    let rooms = await apiFeatures.query;
    let filteredRoomsCount = rooms.length;

    apiFeatures.pagination(resPerPage)
    rooms = await apiFeatures.query;

    res.status(200).json({
        success: true,
        roomsCount,
        resPerPage,
        filteredRoomsCount,
        rooms
    })

})

这是我正在发送有效负载和数据的 redux 操作

    export const getRooms = (req, currentPage = 1, location = '', guests, category) => async (dispatch) => {
    try {

        const { origin } = absoluteUrl(req);

        let link = `${origin}/api/rooms?page=${currentPage}&location=${location}`

        if (guests) link = link.concat(`&guestCapacity=${guests}`)
        if (category) link = link.concat(`&category=${category}`)

        const { data } = await axios.get(link)

        dispatch({
            type: ALL_ROOMS_SUCCESS,
            payload: data
        })

    } catch (error) {
        dispatch({
            type: ALL_ROOMS_FAIL,
            payload: error.response.data.message
        })
    }
}

这是我的 reducer 函数,调度房间数据

export const allRoomsReducer = (state = { rooms: [] }, action) => {
    switch (action.type) {

        case ALL_ROOMS_SUCCESS:
            return {
                rooms: action.payload.rooms
            }

        case ALL_ROOMS_FAIL:
            return {
                error: action.payload
            }

        case CLEAR_ERRORS:
            return {
                ...state,
                error: null
            }

        default:
            return state
    }
}

在这里,我想使用 wrapper.getStaticProps 获取数据,但出现错误,但是当我使用 wrapper.getServerSideProps 时,我得到了数据。

 export const getStaticProps = wrapper.getStaticProps(store=> async ({ req, query, })  => {
  await store.dispatch(getRooms(req, query.page, query.location, query.guests, query.category))
})

【问题讨论】:

  • 错误是什么?
  • 无法读取未定义的页面,

标签: redux next.js next-redux-wrapper


【解决方案1】:

似乎在({ req, query, }) => 中,queryundefined

通过documentation of nextgetStaticPropscontext 对象没有query 属性。它仅适用于getServerSideProps

另见this info

仅在构建时运行 由于 getStaticProps 在构建时运行,因此它不会接收仅在请求期间可用的数据,例如查询参数或 HTTP 标头,因为它会生成静态 HTML。

【讨论】:

    猜你喜欢
    • 2021-01-16
    • 2020-05-16
    • 2021-09-01
    • 2018-06-04
    • 2021-10-05
    • 2021-11-18
    • 2019-11-10
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多