做一个 React 项目并不断遇到类似的问题。在单击时使用 setState 使变量进入状态时遇到问题。在这种情况下,当单击相应的按钮时,我无法将我的播放器对象传递为 ActivePlayer 状态。但是,我可以将其设置为变量,但在应用程序的其他情况下,我需要将其设置为状态,这似乎是最直接的示例。
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import AdminSubNav from 'components/admin-subnav';
import { getPlayers } from 'api/index.js';
import { archivePlayer } from 'api/index.js';
let players = [];
let activePlayer = {};
export default class PlayerView extends React.Component {
constructor(props) {
super(props);
this.state = {
players: [],
activePlayer: {},
player: {}
}
}
componentWillMount() {
getPlayers().then((response) => {
players = response.data;
console.log(players);
this.setState({ players:players });
});
}
onClick(player) {
// let activePlayer = player;
this.setState({
activePlayer:player
});
console.log(activePlayer);
console.log(this.state);
// archivePlayer(this.props.params.id)
// .then(() => {
// this.context.router.push('/player');
// });
}
renderPlayers() {
return players.map((player) => {
return (
<tr key={player.id}>
<td>{player.NameLast}, {player.NameFirst}</td>
<td>{player.teamName}</td>
<td><Link to='/'><i className='material-icons small'>create</i></Link></td>
<td><button onClick={this.onClick.bind(this, player)}><i className='material-icons small'>delete</i></button></td>
</tr>
);
});
}
render () {
return (
<div>
{/*<AdminSubNav title="Player View" route="/team/add"/>*/}
<div className="admin-table-wrapper">
<h3>PLAYERS</h3>
<Link to="/player/add">ADD PLAYER</Link>
<table className="admin-table">
<col className="at-col1"/>
<col className="at-col2"/>
<col className="at-col3"/>
<col className="at-col4"/>
<thead>
<tr>
<th data-field='id'>Player Name</th>
<th data-field='name'>Team</th>
<th data-field='price'>Edit</th>
<th data-field='price'>Archive</th>
</tr>
</thead>
<tbody>
{this.renderPlayers()}
</tbody>
</table>
</div>
</div>
);
}
}