gpt4 book ai didi

javascript - 如何将其添加到函数中以回调 handleChange 和 componentDidMount?

转载 作者:行者123 更新时间:2023-11-30 19:00:37 26 4
gpt4 key购买 nike

如何在handleChange和componentDidMount的回调函数中添加this?

// callback from github api /api.github.com/repos/{user}/{repo}

const [repository, issues] = await Promise.all([
api.get(`/repos/${repoName}`),
api.get(`/repos/${repoName}/issues`, {
params: {
state: 'all',
// I need change this by select options = all, closed and open (per example)
per_page: 5,
},
}),
]);

// this define setState again in handleChange

this.setState({repository: repository.data,
issues: issues.data,
loading: false,
});


// Example:

componentDidMount () {functionUP();};

handleChange () {functionUpAgain(with state from params = all, open or closed);
};

最佳答案

因为您正在使用 await,所以您的函数需要是 async

类似的东西

class YourComponent extends React.Component {
// callback from github api /api.github.com/repos/{user}/{repo}
async fetchData(state = 'all') {
const [repository, issues] = await Promise.all([
api.get(`/repos/${repoName}`),
api.get(`/repos/${repoName}/issues`, {
params: {
state,
// I need change this by select options = all, closed and open (per example)
per_page: 5,
},
}),
]);
// this define setState again in handleChange

this.setState({
repository: repository.data,
issues: issues.data,
loading: false,
});
}

// Example:

componentDidMount() {
this.fetchData();
};

handleChange = () => {
const somestate = 'open'; // here you decide what state to pass to the fetchData
this.fetchData(somestate);
};

render() {

}
}


我无法帮助您了解如何让状态通过 fetchData,因为您的代码没有显示它可能来自哪里。但是示例代码允许将参数传递给 fetchData 方法,该方法将传递给 API。

您还应该考虑重构该代码,以便 api.get(/repos/${repoName}) 不会总是被调用(因为它看起来像它不使用任何参数,并且总是返回相同的数据)

关于javascript - 如何将其添加到函数中以回调 handleChange 和 componentDidMount?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59552895/

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