Redux Dispatch 在 Action Creator 中不起作用

IT技术 reactjs react-native redux react-redux
2021-05-10 20:06:14

我有以下动作创建者,由于某种原因,调度的代码没有执行,尽管我知道loginSuccess()被调用是因为第一个警报触发。我究竟做错了什么?

import facebook from '../api/facebook'
import * as types from '../constants/ActionTypes';

export function loginSuccess() {
  alert("This alerts fine");
  return dispatch => {
    alert("This doesn't alert");
  }
}

创建商店时,我正在使用 Thunk(或至少认为我是正确的),如下所示。

import App from './containers/App';
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import configureStore from './store';
import createReducer from './reducers';
import { createStore, applyMiddleware } from 'redux'
import Parse from 'parse/react-native';
import { AsyncStorage } from 'react-native';
import Settings from './settings';
import thunk from 'redux-thunk'
import logger from 'redux-logger'

const settings = Settings.load();

const middleware = [ thunk, logger() ]

const store = createStore(
    createReducer(),
    applyMiddleware(...middleware)
)

function setup() {
    class Root extends Component {
        render() {
            return (
                <Provider store={store}>
                    <App />
                </Provider>
            );
         }
    }

    return Root;
}

module.exports = setup;

正在调用的组件loginSuccess()如下所示......

import { View, Text } from 'react-native';
import React, { Component,PropTypes } from 'react';
import { loginSuccess,loginError } from '../../../actions/application'
import {
 LoginButton,
 GraphRequest,
 GraphRequestManager,
 GraphRequestConfig,
} from 'react-native-fbsdk'


class FacebookLogin extends Component {

_onLoginSuccess(result){
    loginSuccess();
};

_onLoginError(error){
    loginError();
}

_onLoginCancelled(){

}

render(){
  return (
    <View>
      <LoginButton
        readPermissions={["email","public_profile","user_friends"]}
        onLoginFinished={
          (error, result) => {
            if (error) {
              this._onLoginError(error);
            } else if (result.isCancelled) {
              this._onLoginCancelled();
            } else {
              this._onLoginSuccess(result);
            }
          }
        }
        onLogoutFinished={() => alert("User logged out")}/>
    </View>
  );
}
}

FacebookLogin.propTypes = {
  navigator: PropTypes.object.isRequired,
};

export default FacebookLogin;
2个回答

FacebookLogin组件中有几个错误

  • 该组件未连接到redux做类似的事情export default connect()(FacebookLogin)您需要connectreact-redux
  • 您需要调度loginSuccesss操作而不是直接调用它。所以,你需要做类似的事情this.props.dispatch(loginSuccess())

HTH

是的,您可以在使用 thunk 中间件时调度函数,但下一个函数应该解析为调度动作。如果您只想调用警报,则无需使用 dispatch。

export function loginSuccess() {
  alert("This alerts fine");
  return dispatch => {
    type: 'LOGIN_SUCCESS',
    alertText: 'This doesn't alert'
  }
}

或者

export function loginSuccess() {
  alert("This alerts fine");
  alertAction("This doesn't alert");
}

const alertAction = (text) => (dispatch) => ({
  type: 'LOGIN_SUCCESS',
  alertText: text
})