简体   繁体   English

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

[英]Redux Router - "Dispatch is not defined"

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 loggedIn state of the store to true or false:我有一个简单的组件,当用户加载页面时调用一个操作,在该操作中,我试图分派另一个操作以将商店的loggedIn state 设置为 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 guestLoginRequest action 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 defined when I remove the return dispatch => { } statement.当我删除return dispatch => { }语句时,出现Uncaught ReferenceError: dispatch is not defined错误。 In my store I am using redux-thunk, so I can dispatch inside of actions:在我的商店中,我使用的是 redux-thunk,因此我可以在操作内部进行调度:

// 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?知道为什么我的调度 function 不起作用吗? 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 => { } .我很困惑,因为我确实在我的商店中设置了 redux-thunk,并且我在调用return dispatch => { }时使用了类似于文档的代码。 Is there something I'm missing?有什么我想念的吗? Thank you in advance for any advice!预先感谢您的任何建议!

You need your action to return a function to utilize the thunk middleware, then redux will inject the dispatcher into it. 你需要你的动作来返回一个函数来利用thunk中间件,然后redux会将调度程序注入其中。 You mixed your dispatcher invocation with the implementation detail. 您将调度程序调用与实现细节混合在一起。 The following snippet fixes both defects. 以下代码段修复了这两个缺陷。

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 Login class. 此外,您需要在Login类上正确调度您的操作。

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

Your action invocation is always done by invoking dispatch . 您的操作调用始终通过调用dispatch来完成。 The flow should be something like this: 流程应该是这样的:

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

Make sure useDispatch imported确保已导入useDispatch

import { useDispatch } from "react-redux";

First, you need to import首先,你需要导入

  • import { useDispatch } from "react-redux";

then call it.然后调用它。

  • const dispatch = useDispatch();

now you are ready for use.现在您可以使用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM