[英]React Redux Reducer triggered but not changing state
我正在尝试通过身份验证设置应用程序状态:true和用户数据。 Reducer会被触发(我可以看到console.log),但是它正在返回初始状态(isAuthenticated:false,用户:{})
就我所知,Thunk运行正常
我要加入的道具是{isAuthenticated:否,用户{}}
我之前只是做过这样的事情,所以我不确定为什么会这样
import { AUTHENTICATED } from '../actions/types'
const initialState = {
isAuthenticated: false,
user: {}
}
export default function(state = initialState, action) {
switch (action.type) {
case AUTHENTICATED:
console.log(action.payload)
return {
...state,
isAuthenticated: true,
user: action.payload.user
}
default:
return state
}
}
动作创建者user.js
import axios from 'axios';
import history from '../history';
import config from '../config'
import { AUTHENTICATED } from './types';
export function authUser(token){
return function(dispatch){
const data = {"token": token}
axios.post(`${config.api_url}/authuser`, data)
.then((res) => {
dispatch({type: AUTHENTICATED, payload: res.data})
})
.catch((err) => console.log(err))
}
}
组件dashboard.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import history from '../history';
import * as actions from '../actions/memberActions';
class Dashboard extends Component {
componentWillMount(){
const token = window.localStorage.getItem('token');
if(!token){
history.push('/')
}else{
this.props.authUser(token);
console.log(this.props.user);
}
};
render() {
return (
<div>
<h2>This will be a dashboard page</h2>
<p>There should be something here:{ this.props.authenticated }</p>
<h1>OK</h1>
</div>
)
}
}
function mapStateToProps(state){
return {
user: state.user
}
}
export default connect(mapStateToProps, actions)(Dashboard);
您的代码应该是这样的
export default function(state = initialState, action) {
switch (action.type) {
case AUTHENTICATED:
console.log(action.payload)
return state = {
...state,
isAuthenticated: true,
user: action.payload.user
}
default:
return state
}
}
您正在检查props.user
在componentWillMount
,不显示您的更新。 相反,请检查您的render
方法或另一个生命周期处理程序方法(例如componentWillReceiveProps
的状态更改。
从外观res.data
,好像您的res.data
对象在dispatch({type: AUTHENTICATED, payload: res.data})
中没有user
属性。
因此,当您执行user: action.payload.user
您基本上是在说user: undefined
。
请发布您的console.log(res.data)
以查看是否存在此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.