gpt4 book ai didi

javascript - React 组件无法从 API 映射和渲染数组中的数据

转载 作者:行者123 更新时间:2023-12-01 03:56:54 25 4
gpt4 key购买 nike

我使用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);
});
}
};

This is what my console outputs

最佳答案

您必须在 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>
);

关于javascript - React 组件无法从 API 映射和渲染数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42584960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com