我正在使用react,redux,axios和redux-thunk来处理异步。
我有一种感觉,解决方案将是显而易见的但由于某种原因,我无法映射一组用户(从本地express / node api检索)并渲染每个用户。用户的信息将登录到控制台,但是......
<p>NO USERS FOUND</p>
...组件将呈现在屏幕上。
这是我的回购:https://github.com/tedjames/reduxTest
这就是我的组件的样子:
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { getUsers } from '../redux/actions'
class App extends Component {
componentWillMount() {
console.log(this.props);
this.props.getUsers();
}
render() {
if (this.props.users[1]) {
this.props.users.map((user) => {
console.log("USER FOUND!");
console.log(user.email);
return <p key={user.id}>USER FOUND: {user.email}</p>
});
} else {
return <p>NO USERS FOUND</p>
}
}
}
const mapStateToProps = state => {
return {
users: state.admin.users
};
};
export default connect(mapStateToProps, { getUsers })(App);
这是我使用axios获取用户的行为:
import axios from 'axios'
import { GET_USERS } from './types'
export const getUsers = () => {
return (dispatch) => {
axios.get('http://localhost:3090/users')
.then(res => {
console.log("<-- // DATA RECEIVED FROM SERVER // --> ");
console.log(res);
dispatch({ type: GET_USERS, payload: res.data })
})
.catch(({ response }) => {
console.log("// ERROR RECEIVED FROM SERVER //");
console.log(response);
});
}
};
答案 0 :(得分:1)
你必须在render
内返回数组(并将其包装在某个标签中):
return (
<div>{ this.props.users.map((user) => {
console.log("USER FOUND!");
console.log(user.email);
return <p key={user.id}>USER FOUND: {user.email}</p> }
</div>
);