组件不会渲染所有内容

时间:2019-01-24 07:56:58

标签: reactjs web3

我试图制作一个组件,该组件将返回智能合约(web3库)中的所有信息并返回。当我转到返回该组件内容的页面时-我没有从Smart Contract中看到我的内容。它会稍有延迟地返回,如果我两次进入同一页面,那么我会看到我的内容。

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>
        );
    }
}

1 个答案:

答案 0 :(得分:0)

使用int[] nums= { 5, 6 }; 而不是将元素推送到数组:

  

请勿直接更改this.state,因为之后可能会调用setState()   替换您所做的突变。将this.state视为   不变的。

setState

参考:https://reactjs.org/docs/react-component.html#state