【问题标题】:How to dispatch an action in next.js getStatisProps如何在 next.js getStaticProps 中调度操作
【发布时间】:2020-10-29 05:46:10
【问题描述】:

我是 nextJs 的新手。我希望在 API 调用解决后加载我的组件,并且我想将此 API 调用的响应存储在 redux 存储中。

这是我的组件:-

    const BlogPage = () => {
        return(
            <p>Blogs>
        )
    }

 

export const getStaticProps = async () => {

    const dispatch = useDispatch()

    const nuggetList = await dispatch(getNuggetsList())

    return {
        props: {
            nuggetList
        }
    }
}

Action.js :-

import axios from "axios";
export const GET_NUGGET_LIST = 'GET_NUGGET_LIST'


export const getNuggetsList = () => {
    return(
        async (dispatch) => {
            const res = await axios.get('/blog/nuggets').catch(error => {throw error})
            dispatch({type: GET_NUGGET_LIST, payload: res.data})
            return(res);
        }
    );
}

Reducer.js :-

import { GET_NUGGET_LIST } from "./action";

const initialState = []

export const NuggetList = (state = initialState, action) => {
    switch(action.type){
        case GET_NUGGET_LIST:
            return{...state, nuggetList: action.payload}
        default: 
            return state;
    } 

}

问题是:-

  1. API 请求未发出
  2. 当我将鼠标悬停在组件页面中的await 语句上时,它显示await has no effect on type of this expression

有什么建议吗?

【问题讨论】:

  • 你能解决这个问题吗?
  • 是的...您可以参考接受的答案@Kirasiris
  • 你能分享接受答案的参考吗?

标签: redux next.js


【解决方案1】:

GetStaticProps 只在服务器端运行,这就是你的 redux 逻辑不起作用的原因。您可以在使用 next-redux-wrapper 初始化 _app 页面中的 redux 存储时分派数据

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 2020-12-18
    • 2021-12-30
    • 1970-01-01
    • 2021-02-25
    • 2023-04-03
    • 2021-06-13
    • 1970-01-01
    • 2023-01-04
    相关资源
    最近更新 更多