无法使用 setState onClick 使变量进入状态

Unable to get a variable into state using setState onClick

做一个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>
    );
  }
}

试试这个

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

或者你也可以把它放在构造函数中

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

在您的 renderPlayers 函数中,您正在调用

players.map((player) =>

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

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

在您的 renderPlayers 函数中

我也会尝试在组件的 getInitialState 中设置状态 api

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

您确定这不起作用,还是 console.logs 只是不起作用? setState是一个异步函数,所以如果你设置了state,然后马上去找,可能没有。尝试像这样在 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 的异步性质!

可能是 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