我是reactjs的新手,我正在使用reactjs创建一个演示项目。在我的应用程序中,我在屏幕上显示数据时遇到问题。这是我的代码
import React, {Component} from 'react';
import $ from 'jquery';
import Users from './userlist';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {person: []};
}
componentDidMount() {
console.log("componentDidMount")
this.UserList();
}
UserList() {
return $.getJSON('/react/getUsers')
.then((data) => {
this.setState({ person: data.data });
});
}
render() {
return (
<div>
<Users getUserData = {this.state.person}></Users>
</div>
)
}
}
Home.contextTypes = {
router: React.PropTypes.object.isRequired,
}
在这里调用组件Users
以下是用户组件文件:
import React, {Component} from 'react';
import $ from 'jquery';
export default class Users extends Component {
render() {
console.log(this.props.getUserData)// contains array of objects which am wants to show
return(
<div className="experience-item">
<div className="experience-content experience-color-blue">
<h4>value should be here</h4>
<h6>value should be here</h6>
<p>value should be here</p>
</div>
</div>
)
}
}
答案 0 :(得分:0)
您忘记了构造函数中的bind
UserList
方法
constructor() {
this.state = { person: [] }
this.UserList = this.UserList.bind(this)
}
只要获得结果,只需map
即可。
(我还假设person
至少有id
和name
属性
{this.props.getUserData.map(user => <div key={user.id}>{user.name}</div>)}
答案 1 :(得分:0)
试试以下内容。
1.仅在有数据时才渲染Users
,所以
import React, {Component} from 'react';
import $ from 'jquery';
import Users from './userlist';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {person: []};
}
componentDidMount() {
console.log("componentDidMount")
this.UserList();
}
UserList() {
return $.getJSON('/react/getUsers')
.then((data) => {
this.setState({ person: data.data });
});
}
render() {
return (
<div>
{
(this.state.person && this.state.person.length) ? <Users getUserData = {this.state.person} /> : ""
}
</div>
)
}
}
Home.contextTypes = {
router: React.PropTypes.object.isRequired,
}
迭代用户在用户组件中显示数据
export default class Users extends Component {
render() {
return(
<div>
{
this.props.getUsersData.map((user, index) => {
return (
<div>
<div className="experience-item">
<div className="experience-content experience-color-blue">
<h4>{user.name}</h4>
<h6>{user.details}</h6>
<p>{user.content}</p>
</div>
</div>
)
})
}
<div>
)
}