【发布时间】:2019-10-04 07:52:03
【问题描述】:
我对 react/redux(以及一般的 javascript)还很陌生,所以请耐心等待我在这里使用的术语...
我正在尝试了解组件和减速器的工作原理,因此目前我正在练习一个小应用程序,我主要从教程中复制/粘贴。我遇到的问题是我试图从我的组件中发送一个改变 Redux 状态的操作,但是当我从我的组件发送一个操作时,我什至没有在我的减速器函数中看到我的 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)?我是不是误会了什么?
谢谢
【问题讨论】:
标签: javascript reactjs redux react-redux