gpt4 book ai didi

javascript - 如何在React中正确显示内容

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

我试图显示从我的 api 获取的所有对象,但内容根本没有被渲染。
当我尝试console.log(contact)时,我得到了正确的响应,但没有显示。
console.log(联系人):

(2) [{…}, {…}]
0:{_id: "59c7b975d9d7eed098507a64", contactTitle: "Mrs", …}
1:{_id: "59c86766b3434b06533f3374", contactTitle: "Mr", …}
length:2

还有我的组件:

import _ from 'lodash';
import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { fetchContacts } from '../../actions';

class ContactList extends Component {
componentDidMount() {
this.props.fetchContacts();
}
renderContacts() {
return _.map(this.props.contacts, contact => {
console.log(contact);
return (
<div className="collection" key={contact._id}>
<Link to="/" className="collection-item">
{contact.contactName}
</Link>
</div>
);
});
}

render() {
return (
<div>
<h3>Contacts</h3>
<div>{this.renderContacts()}</div>
</div>
);
}
}

function mapStateToProps({ contacts }) {
return { contacts };
}

export default connect(mapStateToProps, { fetchContacts })(ContactList);

我还有一个 contact.reducer.js:

export default function(state = [], action) {
switch (action.type) {
case FETCH_CONTACTS:
return action.payload;
default:
return state;
}
}

actions.js:

export const fetchContacts = () => async dispatch => {
const res = await axios.get('/api/contacts');

dispatch({type: FETCH_CONTACTS, payload: res.data })
}

我不明白为什么它没有被显示,我在类似的项目中做了同样的事情并且它正在工作。

最佳答案

正如评论中所述(我和@Andy_D),您的 api 响应似乎发送的数据与您预期的不同。您可以在后端更改它,或者:

export const fetchContacts = () => async dispatch => {
const res = await axios.get('/api/contacts');

dispatch({type: FETCH_CONTACTS, payload: res.data.contacts })
}

关于javascript - 如何在React中正确显示内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46407533/

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