0

我是 redux 的新手,我在设置它时遇到了麻烦。

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

也就是说,发出的动作似乎并没有要求我的减速器采取行动。我在我的减速器中尝试了 console.log ,它没有打印任何东西。Thunk显示的当前动作也显示为空,我的initialState没有改变

登录.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>
            );
        }
    }
)

登录动作.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 打印“in request”、“in receive”和“fail :(”。但是,我通过打印有效负载的内容来确保 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 {
    ...
    },
}
4

1 回答 1

0

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

const loginRequested ...
const loginReceived ...

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

于 2018-08-15T15:22:00.847 回答