【发布时间】:2017-04-12 15:43:18
【问题描述】:
我的状态正在从我的操作中获取正确的对象,但它似乎实际上并没有附加到状态。有没有人在 React-Redux 中使用减速器的经验可以提供帮助?我不确定为什么我不能返回新状态。
这是我目前正在编写的代码。
import * as types from '../constants'
const defaultState = {}
const userReducer = (state = defaultState, action) =>{
switch(action.type){
case types.USER_LOGGED_IN:
console.log("in the logged in reducer")
console.log(action.cookie)
return {
...state,
cookie: action.cookie
}
case types.USER_LOGGED_OUT:
return state
default:
return state
}
}
export default userReducer
console.log 实际上会为我打印出正确的 cookie 值。任何想法或帮助将不胜感激。
这里的每个请求都是容器,
import React, { Component, PropTypes } from 'react'
import { routerActions } from 'react-router-redux'
import { connect } from 'react-redux'
import GoogleLogin from '../components/GoogleLogin'
import actions from '../actions/'
import cookie from 'react-cookie'
const login = actions.userActions.login
function select(state, ownProps) {
const isAuthenticated = state.user.cookie || false
console.log(isAuthenticated)
const redirect = ownProps.location.query.redirect || '/'
return {
isAuthenticated,
redirect
}
}
class LoginContainer extends Component {
componentWillMount() {
const { isAuthenticated, replace, redirect } = this.props
if (isAuthenticated) {
replace(redirect)
}
}
componentWillReceiveProps(nextProps) {
const { isAuthenticated, replace, redirect } = nextProps
const { isAuthenticated: wasAuthenticated } = this.props
if (!wasAuthenticated && isAuthenticated) {
replace(redirect)
}
}
onClick(e){
e.preventDefault()
//console.log("in the onClick")
var status = cookie.load("MarketingStatsApp",false)
if(!(status == undefined)){
const login = actions.userActions.login
this.props.login({
cookie: status
})
}
window.location.href='auth/google'
};
render() {
return (
<div>
<h1>Login using Google</h1>
<GoogleLogin onClick={this.onClick.bind(this)}/>
</div>
)
}
}
export default connect(select, { login, replace: routerActions.replace })(LoginContainer)
在这里您可以看到第一次打印出 false,然后打印出 cookie。您甚至可以看到该操作,但我无法单击该操作的箭头,而其他操作未按我的预期显示更新状态
【问题讨论】:
-
这对我来说是正确的。你是如何观察问题的?我怀疑问题出在你在哪里使用状态,而不是在减速器中。
-
是的,你的reducer没问题,请提供你容器的代码
-
感谢您的帮助,我已将容器添加到帖子中
-
你能用所有的日志显示你的整个控制台吗?您也可以在
select方法下记录您的state。 ? -
感谢豹,这是更新
标签: reactjs react-redux