gpt4 book ai didi

javascript - 使用映射函数将状态分配给动态渲染的组件

转载 作者:行者123 更新时间:2023-12-01 00:34:03 25 4
gpt4 key购买 nike

我有一个包含玩家的表,该表是从 API 调用加载并使用 map 函数渲染的。表的最后一列包含一个删除按钮。单击删除按钮时,我想禁用所有其他删除按钮,直到删除调用完成。

这是执行 API 调用以获取玩家的函数。

    loadPlayers() {
const { cookies } = this.props;
const AuthStr = 'Bearer '.concat(this.state.access_token);

axios.get(
configVars.apiUrl + 'team/get-team',
{ headers: { Authorization: AuthStr } }
).then(response => {
var teamArray = response.data;

//Information gotten
this.setState({
teamArray: teamArray,
});

}).catch((error) => {
//Error, remove the access token from cookies and redirect home.
cookies.remove('access_token');
this.props.history.push("/");

});
}
}

映射和渲染是这样完成的:

<Grid item xs={12}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell align="right">Tier</TableCell>
<TableCell align="right">Value</TableCell>
<TableCell align="right">Delete</TableCell>
</TableRow>
</TableHead>
{this.state.teamArray.map((player, i) => {
return <TableBody key={i}>
<TableRow key={i}>
<TableCell align="left">{player.full_name}</TableCell>
<TableCell align="right">{player.tier}</TableCell>
<TableCell align="right">{player.value}</TableCell>
<TableCell align="right">
<IconButton disabled={this.state.deleteDisable}
onClick={() => {this.handleDelete(player.id)}} >
<DeleteIcon />
</IconButton>
</TableCell>
</TableRow>
</TableBody>;
})}
</Table>
</Grid>

handleDelete函数中,我首先将状态中的deleteDisabled设置为true。然而,这没有任何效果,因为一旦表被加载,disabled 就会被设置为 false,并且此后再也不会改变。

如何确保 this.state.deleteDisable 作为变量传递给按钮而不是分配一次?

最佳答案

您应该将玩家存储到state中,然后在render方法中您可以显示table

function loadPlayer() {
const { cookies } = this.props;
const AuthStr = 'Bearer '.concat(this.state.access_token);

axios.get(
configVars.apiUrl + 'team/get-team',
{ headers: { Authorization: AuthStr } }
)
.then(response => this.setState({players: response.data})})
.catch((error) => {
// Error ....
});
}

render() {
return (
...
{
this.state.players((player, i) => (
<TableBody key={i}>
<TableRow>
<TableCell align="left">{player.full_name}</TableCell>
<TableCell align="right">{player.tier}</TableCell>
<TableCell align="right">{player.value}</TableCell>
<TableCell align="right">
<IconButton disabled={this.state.deleteDisabled}
onClick={() => {this.handleDelete(player.id)}} >
<DeleteIcon />
</IconButton>
</TableCell>
</TableRow>
</TableBody>
)}
...
);
}

关于javascript - 使用映射函数将状态分配给动态渲染的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58286193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com