我正在使用React JS和Redux,并且在使用Axios从请求中检索数据时遇到一些问题 .
这是我的Axios请求:
import Axios from 'axios';
class UsersApi {
static getAllUsers() {
return Axios.get('http://localhost:3001/user').then(response => {
return response;
});
}
}
export default UsersApi;
这就是我想要使用我的数据的地方:
import React, {Component} from 'react';
import {connect} from 'react-redux';
class UserList extends Component {
render(){
console.log(this.props.users);
return(
<ul>
</ul>
);
}
}
function mapStateToProps(state) {
return {
users: state.users
};
}
export default connect(mapStateToProps)(UserList);
这是行动:
import UsersApi from '../api/UsersApi';
export function loadUsers() {
return function(dispatch) {
return UsersApi.getAllUsers().then(users => {
dispatch(loadUsersSuccess(users));
}).catch(error => {
throw(error);
});
};
}
export function loadUsersSuccess(users) {
return {type: 'LOAD_USERS_SUCCESS', users};
}
这是我的减速机:
import initialState from './initialState';
export default function usersReducer(state = initialState.users, action) {
switch(action.type) {
case "LOAD_USERS_SUCCESS":
return action.users
default:
return state;
}
}
这就是我对console.log的所作所为:Result console.log
当我尝试显示第一个用户的密码我把console.log(this.props.users.data ["0"] .pwd)但这不起作用..
如果我尝试在请求中返回response.data [“0”] . pwd,我可以使用console.log(this.props.users)获取密码 .
但问题是我想要每个用户的数据..
我需要一些帮助 . :)
2 回答
首先,您需要将用户添加到您的州 . 我看到你正在使用redux,所以你应该在收到你的用户后派遣一个动作并让你的reducer处理它:
你应该有一个名为
usersLoaded
的动作和一个处理它的reducer:这样,您就可以访问
UserList
组件中的用户作为一种正确的还原方式,在你的
get
电话的then
内你需要触发一个动作SET_USERS
,你将使用你的减速器将你的状态替换为从api回来的新用户 .