【发布时间】:2018-08-09 21:51:01
【问题描述】:
我正在尝试使用已验证:真实和用户数据设置应用程序状态。 减速器被触发(我可以看到console.log)但它正在返回初始状态(isAuthenticated:false,用户:{})
据我所知,Thunk 工作正常
我在组件中获得的道具是 {isAuthenticated: false, user{}}
我以前做过类似的事情,所以我不知道为什么会发生这种情况
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);
【问题讨论】:
-
要格式化代码,每一行 必须以 4 个额外空格开头。您可以通过突出显示代码块并按 Ctrl-K 轻松完成此操作。
-
话虽如此,请edit您的问题显示minimal reproducible example。
-
请显示您获得该值的代码。
-
请在
dispatch({type: AUTHENTICATED, payload: res.data})这一行之前写一个console.log。可能是数据变为空白。 -
Action Creator 中没有 console.log 可以很好地返回来自 API 的数据。没问题