反应条件渲染失败

时间:2018-03-05 18:24:59

标签: reactjs redux rendering

我正在尝试使用react组件尝试进行条件渲染但是我一直未尝试为​​标题尝试显示数组最后位置的名称

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

尝试

this.props.users[length -1]

这应该有效。

相关问题