[英]Redux reducers not being called when using dispatch() in Component
我對react / redux(和一般的javascript)相當陌生,因此請允許我繼續使用此處的術語...
我試圖了解Components和Reducers的工作原理,所以目前我正在研究一個小型應用程序,該應用程序大多是從教程中復制/粘貼的。 我遇到的問題是我試圖從Component調度一個動作,這會改變Redux狀態,但是當我從Component調度一個動作時,我什至沒有在我的reducer函數中看到console.log()消息。 。
這是我目前擁有的:
TwApp.js
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { TWAPP_USERDATA_AUTH_TOKEN } from '../Constants'
import { loginSuccess } from '../actions'
class TwApp extends Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.handleRefreshClick = this.handleRefreshClick.bind(this)
}
componentDidMount() {
console.log("TwApp componentDidMount")
this.props.loginSuccess() // This is where I want to dispatch an action
}
componentDidUpdate() {
}
handleChange() {
}
handleRefreshClick(e) {
e.preventDefault()
this.props.loginSuccess()
}
render() {
const { loggedIn } = this.props;
console.log("Rendering TwApp.")
if (!loggedIn) {
console.log("user not logged in. loggedIn = " + loggedIn)
}
else {
return (
<div>
<p>Success</p>
</div>
)
}
}
}
function mapStateToProps(state) {
// nothing for now
}
function mapDispatchToProps(dispatch) {
return {
loginSuccess: () => { dispatch(loginSuccess) }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(TwApp)
actions.js
export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS'
export function loginSuccess() {
return {
type: USER_LOGIN_SUCCESS,
}
}
reducers.js
// Contains a bunch of stuff that isn't being used yet
import { combineReducers } from 'redux'
import {
USER_LOGIN_SUCCESS, INVALIDATE_SUBREDDIT,
REQUEST_POSTS, RECEIVE_POSTS
} from './actions'
function reducer1(state = {}, action) {
console.log("reducer1: state =" + JSON.stringify(state) + ", action = " + JSON.stringify(action))
switch (action.type) {
case USER_LOGIN_SUCCESS:
console.log("Reducer USER_LOGIN_SUCCESS")
state.loggedIn = true
return state
case RECEIVE_POSTS:
case REQUEST_POSTS:
default:
return state
}
}
function reducer2(state = {}, action) {
console.log("reducer2: state =" + JSON.stringify(state) + ", action = " + JSON.stringify(action))
switch (action.type) {
case INVALIDATE_SUBREDDIT:
case RECEIVE_POSTS:
case REQUEST_POSTS:
default:
return state
}
}
const rootReducer = combineReducers({
reducer1,
reducer2
})
export default rootReducer
reducer1或reducer2的console.log()消息都不會出現在控制台中。 當我從TwApp組件調用dispatch()時,是否調用了所有的reducer(reducer1和reducer2)? 我誤會了嗎?
謝謝
您正在分派“ loginSuccess”(它是一個函數),或者用redux術語來分派一個動作創建者。
您應該將動作(它們是簡單的對象)分派給減速器。
您要做的是調度loginSuccess將為您創建的操作:
loginSuccess: () => { dispatch(loginSuccess()) }
comonentDidUpdate,因為您已經擁有它:
componentDidMount() {
console.log("TwApp componentDidMount")
this.props.loginSuccess()
}
然后完全刪除mapDispatchToProps
函數並導出以下內容:
export default connect(mapStateToProps, {loginSuccess})(TwApp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.