【发布时间】:2019-01-24 07:56:58
【问题描述】:
我尝试制作将从智能合约(web3 库)返回所有信息并返回的组件。当我转到返回该组件内容的页面时 - 我没有从智能合约中看到我的内容。它会稍微延迟返回,如果我两次进入同一页面,那么我会看到我的内容。
export default class MyUsers extends React.Component {
constructor(props) {
super(props);
this.state = {
tokens: [],
users: []
};
}
componentDidMount() {
var owner = this.props.match.params.username;
var that = this;
window.smartContract.methods.tokensOfOwner(owner).call().then(function (tokens) {
tokens.map((data, idx) => {
that.state.tokens.push(data);
// Get hero data
window.smartContract.methods.getUsers(data).call().then(function (userData) {
userData.userid = data;
that.state.users.push([userData]);
});
return true;
});
});
}
renderUsers() {
const that = this;
const getUsersInformation = this.state.users.map((data, idx) => {
console.log(data);
var birthTime = new Date(parseInt(data[0].birthTime) * 1000);
return (
<div className="col-md-4" key={idx.toString()}>
<Card>
<CardBody>
<CardTitle className="mb-0">
<h4 className="mb-0">User No. <strong>{ data[0].userid }</strong></h4>
</CardTitle>
<CardSubtitle>
<small>ID No. <strong>{ data[0].id }</strong></small>
</CardSubtitle>
<hr />
<Table>
<tbody>
<tr>
<td className="font-weight-bold">Birthdate:</td>
<td>{ birthTime.getFullYear() }-0{ birthTime.getMonth() + 1 }-0{ birthTime.getDay() + 1 }</td>
</tr>
</tbody>
</Table>
</CardBody>
</Card>
</div>
);
});
return getUsersInformation;
}
render() {
return (
<Card>
<CardBody>
<CardTitle>
<h3>My Users</h3>
</CardTitle>
<hr />
<div className="row">
{this.renderUsers()}
</div>
</CardBody>
</Card>
);
}
}
【问题讨论】:
-
第一次使用 setState 来操纵反应中的状态,以及 2. 检查数据是否存在,例如
this.state.users.length>0 && this.state.users.map(...),因为在您渲染数组的初始时刻,您的数组是空的。并以某种顺序反应初始化组件,构造函数>渲染>componentDidMount>渲染。这就是为什么您需要检查数据是否已加载