我使用Meteor并且有MongoDB作为数据库。 我试着通过" count"自己列出项目编号。变量。 但每次我点击Navbar上的链接时,都会计算而不重置。
例如,第一次点击"联系人"在Navbar上显示如下。
---------------------------------
Contacts Products Solutions
---------------------------------
item user
1 a
2 b
3 c
当我点击"联系人"再次,它显示如下。
---------------------------------
Contacts Products Solutions
---------------------------------
item user
4 a
5 b
6 c
每次单击链接时,如何阻止javascript运行?
在我的代码中,我遇到了" countRegister"变量:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Table, Alert, Button } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Registers } from '../../api/registers';
let countRegister = 0
const DSRegisters = ({ registers, match, history }) => (
<div className="Registers">
<div className="page-header clearfix">
<h4 className="pull-left">Registration</h4>
<Link className="btn btn-success pull-right" to={`${match.url}/new`}>Add User</Link>
</div>
{registers.length ? <Table striped responsive>
<thead>
<tr>
<th>Item</th>
<th>Salution</th>
<th>Firt Name</th>
<th>Last Name</th>
<th>Province</th>
<th>Country</th>
<th>Status</th>
<th>Username</th>
<th />
<th />
</tr>
</thead>
<tbody>
{registers.map(({ _id, regsId, salution, firstname, lastname, province, country, status, username }) => (
<tr key={_id}>
<td>{countRegister += 1}</td>
<td>{salution}</td>
<td>{firstname}</td>
<td>{lastname}</td>
<td>{province}</td>
<td>{country}</td>
<td>{status}</td>
<td>{username}</td>
<td>
<Button
bsStyle="primary"
onClick={() => history.push(`${match.url}/${_id}`)}
block
>View</Button>
</td>
<td>
<Button
bsStyle="danger"
onClick={() => handleRemove(_id)}
block
>Delete</Button>
</td>
</tr>
))}
</tbody>
</Table> : <Alert bsStyle="warning">Nobody yet!</Alert>}
</div>
);
DSRegisters.propTypes = {
registers: PropTypes.arrayOf(PropTypes.object).isRequired,
match: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
};
export default createContainer(() => {
const subscription = Meteor.subscribe('registers');
return {
registers: Registers.find({}, { sort: { regsId: 1 } }).fetch(),
};
}, DSRegisters);
答案 0 :(得分:1)
如果要在每次渲染组件时显示1,2,3,则不应使用全局变量countRegister
。这里的问题是,只要您不刷新网站,您的countRegister
变量将永远不会重置为0,因为它是一个仅初始化一次的全局变量,因此计数将继续增加。
相反,您可以使用map
方法的第二个参数,nl,索引
registers.map(({
_id,
regsId,
salution,
firstname,
lastname,
province,
country,
status,
username
}, index) => ( // <- index is the second argument, starting from 0
<tr key={_id}>
<td>{( index + 1)}</td> // <- so to show 1, 2, 3, increase it by 1
<td>{salution}</td>
// ...
这将使您的计数保持您想要的方式