He intentado crear una lista de objetos de 'Liga' desde el servidor, el usuario puede hacer clic para crear una liga con éxito, pero para unirse a una liga, el usuario deberá hacer clic en el icono y el parámetro deberá enviarse a joinLeague () ya que la API requiere league.leagueId para unirse a la liga:
Componente LeagueList:
constructor(props) { super(props); this.state = { leagues: [] }; this.createLeague = this.createLeague.bind(this); this.joinLeague = this.joinLeague.bind(this); } joinLeague() { const payload = { "username": localStorage.getItem("username"), "leagueId": }; fetch(JOIN_LEAGUE_URL, { method: 'POST', headers: { "Accept": "application/json", "Content-Type": "application/json", "Authorization": localStorage.getItem("token") }, body: JSON.stringify(payload) }) .then(response => response.json()) .then(); } render() { const {leagues} = this.state; const leagueList = leagues.map(league => { return <tr key={league.leagueId}> <td style={{whiteSpace: 'nowrap'}}>{league.leagueCreatorUsername}</td> <td>{league.playerCount}/10</td> <td>{league.matchesPerPlayer}</td> <td>{league.numberOfGamesPlayed}</td> <td>{league.totalGamesToBePlayed}</td> <i className="fas fa-plus" onClick={this.joinLeague}></i> </tr> });}
En la función joinLeague() anterior, puede ver que estoy tratando de crear la carga útil, pero necesito el leagueId de como parámetro.
¿Cómo puedo lograr esto? Probé {this.joinLeague.bind(league)} pero no funcionó, gracias.
Si usa una función de flecha, debería vincularse al alcance (manteniendo el valor actual de league )
¿Podrías intentar algo como esto?
render() { const {leagues} = this.state; const leagueList = leagues.map(league => { return <tr key={league.leagueId}> <td style={{whiteSpace: 'nowrap'}}>{league.leagueCreatorUsername}</td> <td>{league.playerCount}/10</td> <td>{league.matchesPerPlayer}</td> <td>{league.numberOfGamesPlayed}</td> <td>{league.totalGamesToBePlayed}</td> <i className="fas fa-plus" onClick={() => this.joinLeague(league.leagueId)}></i> </tr> }); } joinLeague(leagueId) { const payload = { "username": localStorage.getItem("username"), "leagueId": leagueId }; fetch(JOIN_LEAGUE_URL, { ... Aquí hay un enlace a un ejemplo mínimo, que muestra que leagueId ahora está disponible en joinLeague