gpt4 book ai didi

javascript - react : Async function not being called

转载 作者:行者123 更新时间:2023-11-30 10:57:20 26 4
gpt4 key购买 nike

为什么我的 aync 调用 fetchButtonTeams() 没有被调用。我试图在下面的 console.log(this.state.data) 中打印它的结果。即使我在 render() 中调用它,我也会遇到无限循环或错误。谁能建议怎么做?

我只想在 render() 的 console.log 中打印结果

class TeamFilter extends Component {
constructor() {
super();
this.state = { data: [] };
}

async fetchButtonTeams() {
const response = await fetch(`/api/teams`);
const json = await response.json();
console.log(json)
this.setState({ data: json });
}

handleTeamSelection = e => {
this.props.setTeam(e.target.title);
this.props.fetchTeams(e.target.title)
};


render() {

let test = ['Chaos', 'High Elves', 'Orcs']

this.fetchButtonTeams()

console.log(this.state.data)

return (
<DropdownButton id="dropdown-team-button" title={this.props.team_name}>
{test.map(cls => (
<div key={cls}>
<Dropdown.Item onClick={this.handleTeamSelection} title={cls}>{cls}</Dropdown.Item>
</div>
))}
</DropdownButton>
)
}


}

const mapStateToProps = state => {
return {
team_name: state.team_name
}
};

const mapDispatchToProps = dispatch => {
return {
fetchCards: path => dispatch(fetchCards(path)),
fetchTeams: params => dispatch(fetchTeams(params)),
setTeam: team_name => dispatch({ type: "SET_TEAM", team_name })
}
};




export default connect(mapStateToProps, mapDispatchToProps)(TeamFilter)

最佳答案

render 方法上调用该函数时出现无限循环的原因是每次该函数都调用 setState 而后者又一次又一次地运行该函数,触发无限循环。

我看不到您在组件中的任何地方调用 fetchButtonTeams(),但是获取数据的一个好主意是将该方法放在 componentDidMount 生命周期方法中和渲染方法中的控制台日志。您可以了解有关生命周期 Hook 的更多信息 here .

对于您的代码:

class TeamFilter extends Component {
constructor() {
super();
this.state = { data: [] };
}

componentDidMount() {
this.fetchButtonTeams();
}

async fetchButtonTeams() {
const response = await fetch(`/api/teams`);
const json = await response.json();
console.log(json);
this.setState({ data: json });
}

handleTeamSelection = e => {
this.props.setTeam(e.target.title);
this.props.fetchTeams(e.target.title);
};

render() {
let test = ["Chaos", "High Elves", "Orcs"];

console.log(this.state.data);

return (
<DropdownButton id="dropdown-team-button" title={this.props.team_name}>
{test.map(cls => (
<div key={cls}>
<Dropdown.Item onClick={this.handleTeamSelection} title={cls}>
{cls}
</Dropdown.Item>
</div>
))}
</DropdownButton>
);
}
}

const mapStateToProps = state => {
return {
team_name: state.team_name
};
};

const mapDispatchToProps = dispatch => {
return {
fetchCards: path => dispatch(fetchCards(path)),
fetchTeams: params => dispatch(fetchTeams(params)),
setTeam: team_name => dispatch({ type: "SET_TEAM", team_name })
};
};

export default connect(mapStateToProps, mapDispatchToProps)(TeamFilter);

关于javascript - react : Async function not being called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59485133/

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