减速器未在调用调度时触发

时间:2018-08-15 14:41:31

标签: reactjs redux react-redux redux-thunk redux-persist

我是Redux的新手,但设置时遇到了麻烦。

每当我单击登录按钮时,我都试图调度一个动作。但是reducer不会被调用。使用Thunk,我可以看到我的动作确实被调度了。每当我单击登录按钮并且成功使用LoginAction.js中的console.log时,我的终端就会打印前一状态,当前操作和下一状态。

也就是说,发出的动作似乎没有调用我的减速器来动作。我在我的reducer中尝试了console.log,但它不打印任何内容。 Thunk显示的当前操作也显示为空,并且我的initialState不变

Login.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { login } from './LoginAction';

const mapDispatchToProps = (dispatch) => {
    return{
        login: () => {dispatch(login())},
    }
};

const mapStateToProps = (state) => {
    return{
        userInfo: state.userInfo
    }
};

const Login = connect(mapStateToProps, mapDispatchToProps)(
    class Login extends Component {
        onLogin() {
            this.props.login();
        }

        render() {
            return (
                <View>
                    <TouchableHighlight 
                        onPress={() => this.onLogin()}>
                    </TouchableHighlight>
                </View>
            );
        }
    }
)

LoginAction.js

import { URL } from '../../core/api';
import { fetchPost } from '../../core/util';

export const LOGIN_REQUESTED = "LOGIN_REQUESTED";
loginRequested = () => {
    console.log("in request");
    return {
        type: LOGIN_REQUESTED,
    };
}


export const LOGIN_RECEIVED = "LOGIN_RECEIVED";
loginReceived = (loginAttemptResult) => {
    console.log("in receive");
    console.log(JSON.stringify(loginAttemptResult));
    return {
        type: LOGIN_RECEIVED,
        loginAttemptResult
    };
}

export function login() {
    let loginApi = URL + "/login";
    console.warn(loginApi)

    return (dispatch) => {
        dispatch(loginRequested());
        const formData = {
            email: 'xxx@gmail.com',
            id: '000000000000'
        }
        fetchPost(loginApi, formData)
            .then(loginAttemptResult => {
                console.log(loginAttemptResult);
                dispatch(loginReceived(loginAttemptResult));
            })
            .catch(console.log("fail :("));
    };
}

在LoginAction.js中,我的console.log打印“请求中”,“接收中”和“失败:(”。但是,我已经通过打印HttpRequest / Fetch的内容来确保HttpRequest / Fetch成功有效载荷

LoginReducer.js

import {LOGIN_REQUESTED, LOGIN_RECEIVED} from "./LoginAction";
import {RESPONSE_STATUS} from "../../constants";
import {userInfoState} from "../../core/initialState";

export default function loginReducer(state = userInfoState, action) {
    switch (action.type) {
        case LOGIN_REQUESTED:{
            console.log("reducer 1");
            return Object.assign({}, state, {
                isLoggingIn: true
            });
        }
        case LOGIN_RECEIVED: {
            console.log("reducer 2");
            const {status, message} = action.loginAttemptResult;
            const errorMsg = (status === RESPONSE_STATUS.ERROR) && message;
            return Object.assign({}, state, {
                isLoggingIn: false, errorMsg,
            });
        }
        default:
             console.log("default reducer");
             return state;
    }
}

LoginReducer.js中的任何内容都没有打印在我的控制台中

store.js

import { AsyncStorage } from 'react-native';
import { createStore, applyMiddleware, compose } from 'redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import { REHYDRATE, persistCombineReducers } from 'redux-persist';
import createActionBuffer from 'redux-action-buffer';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2'

import loginReducer from '../screens/Login/LoginReducer';

let storage = AsyncStorage;

const config = {
    key: 'root',
    storage,
    stateReconciler: autoMergeLevel2
}

export default function configureStore() {

    let reducer = persistCombineReducers(config, {
        userInfo: loginReducer,
    });

    const middleware = [thunk];
    middleware.push(createLogger());

    middleware.push(createActionBuffer(REHYDRATE));
    const store = createStore(
        reducer,
        undefined,
        compose(applyMiddleware(...middleware)),
    );

    persistStore(
        store,
        null,
    );
    return store;
}

我的怀疑是store.js出现了问题,但我无法弄清楚。

这是我在网站上遇到的第一个问题,英语不是我的母语。如果不清楚并需要澄清,请询问

编辑:这是来自thunk的日志

Login button clicked
in request
action LOGIN_REQUESTED 
prev state Object {
    "userInfo": Object {...},
}
action Object {
    "type": "LOGIN_REQUESTED",
}
next state Object {
    "userInfo": Object {...},
}
fail :(
Object {
    "data": Array [
            Object {
                ...
            },
        ],
    "message": "success",
    "status": 1,
}
in receive
action Object {
    "loginAttemptResult": Object {
        "data": Array [
            Object {...},
        ],
        "message": "success",
        "status": 1,
    },
    "type": "LOGIN_RECEIVED",
}
next state Object {
    "userInfo": Object {
    ...
    },
}

1 个答案:

答案 0 :(得分:0)

我无法检查所有代码(例如对我来说很复杂的商店),但是我在这里看到的唯一错误是您没有在动作创建者中正确定义loginRequestedloginReceived函数文件。

const loginRequested ...
const loginReceived ...

因此,也许根本不会触发它们,并且您的操作不会影响减速器。