反应条件渲染失败

问题描述 投票:0回答:2

我正在使用一个反应组件试图进行条件渲染,但我一直在试图显示数组最后位置的名称未定义

class Users extends Component {
    static propTypes = {
        users: PropTypes.arrayOf(PropTypes.shape({}))
    };

    static defaultProps = {
        users: []
    };
    renderContent() {

        const length = (this.props.users.length);
        return (
            <Row>
                <Col sm={12}>
                <Table responsive striped bordered>
                        <thead>
                        <tr>
                            <th>Name</th>
                            <th>Country</th>
                            <th>BirthDay</th>
                        </tr>
                        </thead>
                        <tbody>
                        {this.props.users.map(user => (
                            <tr key={user.name + user.surname + user.countries + user.birthday} className="table-vertical-middle ta-user-row">
                                <td className="ta-username">{user.name} {user.surname}</td>
                                <td className="ta-country">{user.countries}</td>
                                <td className="ta-birthday">{user.birthday}</td>
                            </tr>
                        ))}
                        </tbody>
                    </Table>
                </Col>
                <Row>
                    <Col sm={12}>
                        <h2>{this.props.users[length].name} {this.props.users[length].surname}</h2>
                    </Col>
                </Row>
            </Row>


        );
    }

在这里我做了条件,除非你有数据,否则不要渲染

render() {
    return (
        <Grid>
            {this.props.users && this.renderContent()}
        </Grid>
    );
}
   }

连接到redux

export default connect(
    state => ({users: state.user.users}),
)(Users);
reactjs redux rendering
2个回答
0
投票

这是因为您正在以未定义的索引访问users数组。尝试以下方法。

<h2>{this.props.users[length - 1].name} {this.props.users[length - 1].surname}</h2>

0
投票

尝试

this.props.users[length -1]

这应该工作。

© www.soinside.com 2019 - 2024. All rights reserved.