Javascript Redux 路由器 - “未定义调度”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36462284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:07:04  来源:igfitidea点击:

Redux Router - "Dispatch is not defined"

javascriptreactjsreduxreact-reduxredux-thunk

提问by Mike

I've got a simple component that calls an action when a user loads a page, and inside that action, I'm trying to dispatch another action to set the loggedInstate of the store to true or false:

我有一个简单的组件,它在用户加载页面时调用一个动作,在该动作中,我试图调度另一个动作以将loggedIn商店的状态设置为 true 或 false:

import React, { Component } from 'react'
import { Link, browserHistory } from 'react-router'
import $ from 'jquery'

class Login extends Component {

  constructor(props) {
    super(props)
  }
  componentDidMount() {
    this.props.actions.guestLoginRequest()
  }
  render() {
    return (
      <div>
        <div classNameName="container">
          <div className="row">
            We are signing you in as a guest
          </div>
        </div>
      </div>
    )
  }
}

export default Login

I can get the login information when the guestLoginRequestaction is called, but when I try to dispatch another action inside of it, nothing happens:

我可以在guestLoginRequest调用操作时获取登录信息,但是当我尝试在其中调度另一个操作时,没有任何反应:

guestLoginRequest: function(){
    var ref = new Firebase("https://penguinradio.firebaseio.com");
    ref.authAnonymously(function(error, authData) {
      if (error) {
        console.log("Login Failed!", error);
      } else {
        console.log("Authenticated successfully with payload:", authData);
        return dispatch => {
          dispatch(actions.setLoginStatus(true, authData))
          console.log("dispatched");
        };
      }
    });
  }

I get an error of Uncaught ReferenceError: dispatch is not definedwhen I remove the return dispatch => { }statement. In my store I am using redux-thunk, so I can dispatch inside of actions:

Uncaught ReferenceError: dispatch is not defined删除return dispatch => { }语句时出现错误。在我的商店中,我使用的是 redux-thunk,所以我可以在 action 内部调度:

// Store.js
import { applyMiddleware, compose, createStore } from 'redux'
import rootReducer from './reducers'
import logger from 'redux-logger'
import thunk from 'redux-thunk'

let finalCreateStore = compose(
  applyMiddleware(thunk, logger())
)(createStore)


export default function configureStore(initialState = { loggedIn: false }) {
  return finalCreateStore(rootReducer, initialState)
}

I am mapping the dispatch to props in my app.js as well:

我也在 app.js 中将调度映射到道具:

function mapStateToProps(state) {
  return state
}
function mapDispatchToProps(dispatch) {
  return {
      actions: bindActionCreators(actions, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App)

Just in case it could be helpful, here is my client.js and reducer files:

以防万一它会有所帮助,这是我的 client.js 和 reducer 文件:

// client.js
import React from 'react'
import { render } from 'react-dom'
import App from '../components/App'
import configureStore from '../redux/store'
import { Provider } from 'react-redux'


let initialState = {
  loggedIn: false
}

let store = configureStore(initialState)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app')
)
// Reducer.js
import { combineReducers } from 'redux'

let LoginStatusReducer = function reducer(loggedIn = false, action) {
  switch (action.type) {
    case 'UPDATE_LOGIN_STATUS':
      return loggedIn = action.boolean
    default:
      return loggedIn
  }
}
export default LoginStatusReducer

const rootReducer = combineReducers({
  loggedIn: LoginStatusReducer
})

export default rootReducer

Any ideas why my dispatch function isn't working? I'm confused since I did set up redux-thunk with my store, and I'm using code similar to the docs when I call return dispatch => { }. Is there something I'm missing? Thank you in advance for any advice!

任何想法为什么我的调度功能不起作用?我很困惑,因为我确实在我的商店中设置了 redux-thunk,而且我在调用return dispatch => { }. 有什么我想念的吗?预先感谢您的任何建议!

回答by Matt Lo

You need your action to return a function to utilize the thunk middleware, then redux will inject the dispatcher into it. You mixed your dispatcher invocation with the implementation detail. The following snippet fixes both defects.

您需要您的操作返回一个函数来使用 thunk 中间件,然后 redux 会将调度程序注入其中。您将调度程序调用与实现细节混合在一起。以下代码段修复了这两个缺陷。

guestLoginRequest: function(){
  return function (dispatch) {
    var ref = new Firebase("https://penguinradio.firebaseio.com");
    ref.authAnonymously(function(error, authData) {
      if (error) {
        console.log("Login Failed!", error);
      } else {
        console.log("Authenticated successfully with payload:", authData);
        dispatch(actions.setLoginStatus(true, authData))
        console.log("dispatched");
      }
    });
  }
}

In addition, you need to dispatch your action correctly on the Loginclass.

此外,您需要在Login类上正确发送您的操作。

dispatch(this.props.actions.guestLoginRequest())

Your action invocation is always done by invoking dispatch. The flow should be something like this:

您的操作调用始终通过调用dispatch. 流程应该是这样的:

React component --> dispatch ---> API call (thunk middleware) --> dispatch ---> reducer