我've got a simple component that calls an action when a user loads a page, and inside that action, I'm试图发送另一个动作来将商店的 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
我可以在调用 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");
};
}
});
}
当我删除 return dispatch => { }
语句时,我收到 Uncaught ReferenceError: dispatch is not defined
的错误 . 在我的商店,我使用的是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)
}
我也将调度映射到app.js中的props:
function mapStateToProps(state) {
return state
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
为了防止它有用,这里是我的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
因为我在我的商店中设置了redux-thunk,并且在调用 return dispatch => { }
时我正在使用与文档类似的代码,所以为什么我的调度函数不是很困惑 . 有什么我想念的吗?提前感谢您的任何建议!
1 回答
你需要你的动作来返回一个函数来利用thunk中间件,然后redux会将调度程序注入其中 . 您将调度程序调用与实现细节混合在一起 . 以下代码段修复了这两个缺陷 .
此外,您需要在
Login
类上正确调度您的操作 .您的操作调用始终通过调用
dispatch
来完成 . 流程应该是这样的: