javascript - React Redux 无法与 Next.js 和 NodeJS 一起正常工作

标签 javascript node.js reactjs redux next.js

我正在按照 this example 开发一个使用 Next.js 和 redux 的应用程序这是 store.js

的一部分
// REDUCERS
const authReducer = (state = null, action) => {
    switch (action.type){
        case actionTypes.FETCH_USER:
            return action.payload || false;
        default:
            return state;
    }
}

export const rootReducer = combineReducers({
    user: authReducer,
    form: reduxForm,
});

// ACTIONS
export const fetchUser = () => {
    return (dispatch) => {
        axios.get('/api/current_user')
            .then(res => dispatch({
                type: actionTypes.FETCH_USER, 
                payload: res.data
            }));
    };
};

export const submitLogin = (values) => async dispacth => {
    const res = await axios.post('/api/login', values);

    // Router.push('/');
    // console.log(res)

    dispacth({ type: actionTypes.SUBMIT_LOGIN, payload: res.data });
};

和客户端如header

function mapStateToProps (state) {
    const { user } = state
    return { user }
}

export default connect(mapStateToProps)(Header)

当我 console.log('############=>', this.props.user); props & 我没有登录然后它显示为 null 但显示一些额外的数据,例如下面的屏幕截图

enter image description here

但是当我登录 & console.log('############=>', this.props.user); 它显示正确的数据而没有额外的数据如下图

enter image description here

我做错了什么?请帮我。谢谢

最佳答案

问题可能不在您的 React/Redux 代码上,而在您的 Next.js 路由上。

您正尝试使用 axios.get('/api/current_user') 调用 API,但 Next.js 给您一个 HTML 响应,您确实存储在 authReducer 中 将其提取为 action.payload

你可能想看 this section about Custom Server and Routing .

关于javascript - React Redux 无法与 Next.js 和 NodeJS 一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56823619/

相关文章:

node.js - 直接从网络中外部node.js服务器上的uv4l服务器读取流

javascript - jquery 查找下一个带有类的元素

javascript - 如何使用 requireJS 调用多个函数

javascript - 如何通过从 json 文件获取数据来创建可编辑表?

javascript - 实现 toJSON() 方法是否足以使任何类实例可序列化?

javascript - React - 单击位于组件外部的按钮时重新渲染组件

javascript - 使嵌套模式虚拟 Mongoose 的验证无效

angularjs - Ubuntu:错误:EACCES,使用 Bower 安装时出现权限被拒绝错误

css - 内联样式 react 元素宽度

javascript - react : Parsing error: Unexpected token, 预期 "..."