Javascript 如何在react.js中使用json
以下是json格式的数据: 这是我的密码。运行它之后,我在console.log中遇到错误:“对象作为React子对象无效(找到:具有键{userId,id,title,body}的对象)。如果您想呈现子对象的集合”。 为什么当我在componentDidMount中使用console.log(response)时,我有我的对象数组,但不能在render(){}中使用它。我做错了什么Javascript 如何在react.js中使用json,javascript,json,reactjs,jsx,Javascript,Json,Reactjs,Jsx,以下是json格式的数据: 这是我的密码。运行它之后,我在console.log中遇到错误:“对象作为React子对象无效(找到:具有键{userId,id,title,body}的对象)。如果您想呈现子对象的集合”。 为什么当我在componentDidMount中使用console.log(response)时,我有我的对象数组,但不能在render(){}中使用它。我做错了什么 class App extends React.Component { constructor(prop
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')
);
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
this.state={
用户:[]
}
}
componentDidMount(){
var分量=此;
api.fetchInfo()
.然后(功能(响应){
setState({users:response});
});
}
render(){
//log('here'+this.state.users);
返回(
{this.state.users}
{
this.state.users.map(
功能(elem){
返回- {elem.userId}
}
)
}
)
}
}
ReactDOM.render(
,
document.getElementById('app')
);
这一行jsx:
<p>{this.state.users}</p>
否则,您可能希望
映射并呈现对您有意义的标记。问题是由行引起的
<p>{this.state.users}</p>
上面的块返回有效的jsx,它是一组
元素。那些
元素本身有一个{elem.userId}
,可以直接解释为字符串 我不知道该怎么做。我和react在一起的第三天,对我来说仍然很奇怪:)
<p>{this.state.users}</p>
<p>{JSON.stringify(this.state.users)}</p>
{
this.state.users.map(
function(elem) {
return <li>{elem.userId}</li>
}
)
}