无法使用setState onClick将变量置于状态

时间:2016-02-09 22:52:12

标签: javascript reactjs state setstate

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

4 个答案:

答案 0 :(得分:1)

试试这个

{this.renderPlayers.bind(this)()}

或者您也可以将它放在构造函数

constructor(props) {
    super(props);
    this.state = {
      players: [],
      activePlayer: {},
      player: {}
    }
    this.renderPlayers = this.renderPlayers.bind(this);
}

答案 1 :(得分:0)

在您的renderPlayers功能上,您正在调用

players.map((player) =>

这将引用顶级玩家阵列。我会试试

this.state.players.map((player) =>

在你的renderPlayers函数

我还会尝试在组件api上的getInitialState中设置你的状态

getInitialState() {
  return {
          players: [],
          activePlayer: {},
          player: {}
         }
}

答案 2 :(得分:0)

你确定这不起作用,还是console.logs不起作用? setState是一个异步函数,所以如果你设置状态,然后在它可能不存在之后立即查找它。尝试使用setState中的回调,如下所示:

this.setState({ /* state */ },() => {
   // console.log and check stuff
   // Also do any other function calls that you need to to explicitly   after the state has been updated
})

不确定这是否会解决它,但记住setState的异步特性非常重要!

答案 3 :(得分:0)

问题可能出在 onClick 出价上。

我遇到了同样的问题并通过出价 onClick 处理程序解决了这个问题,试试这个:

constructor(props) {
    super(props);
        this.state = {
          players: [],
          activePlayer: {},
          player: {}
        }
       this.onClick = this.onClick.bind(this);
    }

您可以在 React 文档中看到它:https://reactjs.org/docs/handling-events.html