gpt4 book ai didi

javascript - react 不变违规 : Objects are not valid as a React child

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:31:40 28 4
gpt4 key购买 nike

我有以下代码:

import ReactDom from 'react-dom';
import React from 'react';
import {render} from 'react-dom';
import $ from 'jquery';


class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: '',
loading: true
}
}
componentDidMount () {
const newsfeedURL = 'https://s3-eu-west-1.amazonaws.com/streetlife-coding-challenge/newsfeed.json';
$.get(newsfeedURL, function(result) {
this.setState({
data: JSON.parse(result),
loading: false
});
console.log(typeof this.state.data.messages);
}.bind(this));
}
render () {
let content;
if (this.state.loading === false && this.state.data.messages) {
content = Object.keys(this.state.data.messages).map(key => {
return <div key={key}>Key: {key}, Value: {this.state.data.messages[key]}</div>;
})
} else {
content = ''; // whatever you want it to be while waiting for data
}
return (
<div>
{content}
</div>
)
}
}


ReactDom.render(
<App />,
document.getElementById('app')
);

但我收到以下错误:

未捕获的不变违规:对象作为 React 子项无效(已找到:具有键 {body、attachments、videos、topics、updated_at、id、subject、downvotes、author、posted_at、comments、user_vote、upvotes 的对象、状态、标签、位置、track_impact、user_is_following、comments_count})。如果您打算渲染子集合,请改用数组或使用 React 附加组件中的 createFragment(object) 包装对象。检查 App 的渲染方法。

我看过这个答案,但它对我的情况没有帮助:Invariant Violation: Objects are not valid as a React child

最佳答案

在您的 div 中,您正在尝试呈现 Value: {this.state.data.messages[key]} 这是一个对象。你不能直接使用 React 的 JSX 渲染对象。然而,您可以呈现的是该对象中保存的一些实际原始数据类型(例如字符串、数字),例如 Value: {this.state.data.messages[key].body} 将呈现保存在对象的 body 属性中的字符串值。这是一个演示:http://codepen.io/PiotrBerebecki/pen/bwowxP

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: '',
loading: true
}
}
componentDidMount () {
const newsfeedURL = 'https://s3-eu-west-1.amazonaws.com/streetlife-coding-challenge/newsfeed.json';
$.get(newsfeedURL, function(result) {
this.setState({
data: JSON.parse(result),
loading: false
});
console.log(typeof this.state.data.messages);
}.bind(this));
}
render () {
let content;
if (this.state.loading === false && this.state.data.messages) {
content = Object.keys(this.state.data.messages).map(key => {
console.log(this.state.data.messages[key])
return <div key={key}><b>Key: {key},</b> Value: {this.state.data.messages[key].body}</div>;
})
} else {
content = ''; // whatever you want it to be while waiting for data
}
return (
<div>
{content}
</div>
)
}
}


ReactDOM.render(
<App />,
document.getElementById('app')
);

关于javascript - react 不变违规 : Objects are not valid as a React child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806069/

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