如何在 react.js 中使用 json
how to work with json in react.js
json 中的数据:https://jsonplaceholder.typicode.com/posts
这是我的代码。在 运行 之后,我在 console.log 中出错:"Objects are not valid as a React child (found: object with keys {userId, id, title, body}). If you meant to render a collection of children"。
为什么当我在 COmpoonentDidMount 中 console.log(response) 我有我的对象数组但不能在 render() {} 中使用它。我做错了什么?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
users: []
}
}
componentDidMount() {
var component = this;
api.fetchInfo()
.then(function(response) {
component.setState( { users: response } );
});
}
render() {
//console.log('here' + this.state.users);
return (
<ul>
<p>{this.state.users}</p>
{
this.state.users.map(
function(elem) {
return <li>{elem.userId}</li>
}
)
}
</ul>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
jsx这一行:
<p>{this.state.users}</p>
要求 React 渲染一个普通对象。它不知道如何为你做那件事。如果你想 json 被打印到页面,你可以 stringify
它:
<p>{JSON.stringify(this.state.users)}</p>
否则,您可能想要 map
浏览并呈现对您有意义的标记。
问题是由行
引起的
<p>{this.state.users}</p>
您可以删除它或使用:
<p>{JSON.stringify(this.state.users)}</p>
简而言之,解释是这样的:
- 在任何 jsx 块中,您可以将 javascript 嵌入大括号内,即
{}
{}
块中 javascript 的结果必须是:字符串、null 或其他有效的 jsx 对象。如果是其他情况,您将看到您看到的错误。
在你的情况下,你还有一个有效的块:
{
this.state.users.map(
function(elem) {
return <li>{elem.userId}</li>
}
)
}
上面的块返回有效的 jsx,它是一堆 <li>
元素。那些 <li>
元素本身有一个 {elem.userId}
可以直接解释为一个字符串。
json 中的数据:https://jsonplaceholder.typicode.com/posts
这是我的代码。在 运行 之后,我在 console.log 中出错:"Objects are not valid as a React child (found: object with keys {userId, id, title, body}). If you meant to render a collection of children"。 为什么当我在 COmpoonentDidMount 中 console.log(response) 我有我的对象数组但不能在 render() {} 中使用它。我做错了什么?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
users: []
}
}
componentDidMount() {
var component = this;
api.fetchInfo()
.then(function(response) {
component.setState( { users: response } );
});
}
render() {
//console.log('here' + this.state.users);
return (
<ul>
<p>{this.state.users}</p>
{
this.state.users.map(
function(elem) {
return <li>{elem.userId}</li>
}
)
}
</ul>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
jsx这一行:
<p>{this.state.users}</p>
要求 React 渲染一个普通对象。它不知道如何为你做那件事。如果你想 json 被打印到页面,你可以 stringify
它:
<p>{JSON.stringify(this.state.users)}</p>
否则,您可能想要 map
浏览并呈现对您有意义的标记。
问题是由行
引起的<p>{this.state.users}</p>
您可以删除它或使用:
<p>{JSON.stringify(this.state.users)}</p>
简而言之,解释是这样的:
- 在任何 jsx 块中,您可以将 javascript 嵌入大括号内,即
{}
{}
块中 javascript 的结果必须是:字符串、null 或其他有效的 jsx 对象。如果是其他情况,您将看到您看到的错误。
在你的情况下,你还有一个有效的块:
{
this.state.users.map(
function(elem) {
return <li>{elem.userId}</li>
}
)
}
上面的块返回有效的 jsx,它是一堆 <li>
元素。那些 <li>
元素本身有一个 {elem.userId}
可以直接解释为一个字符串。