我的问题很简单,但我缺少这个过滤过程的某些部分。 我试图将我的组件状态设置为我为复选框输入提供的任何值,并且仅当该值与单击事件后 API 中的数据数组匹配时才返回我的状态。
虽然它在我的 Chrome 控制台中正确记录了数据,但我一直在努力将记录的数据设置到我的组件状态中,但没有成功......
我的最终目标是:
第 1 部分 - 在单击事件后输出组件状态中的正确数据。
第 2 部分 - 取消选中输入后获取初始数据。
第 3 部分 - 如果选中超过 1 个复选框,则能够输出多个数据。
第 1 部分代码
handleFilterButtons = (event) => {
var valueInput = event.target.value;
var apiFilters = `https://backend.greatsaigon.com/api/v1/en/venues`;
axios.get(apiFilters)
.then( (response) =>{
this.setState({
result: response.data.filter((req) => {
if (req.options.beauty.hair.treatment !== "0") {
req.options.beauty.hair.treatment.filter((res) => {
if (res === valueInput) {
console.log(req)
}
})
}
})
})
})
.catch(function (error) {
console.log(error);
})
}
最佳答案
我不认为你想在这里使用的功能是过滤器。过滤器内的返回值是 bool 值,但您在另一个过滤器内使用过滤器。但是,您可以使用 forEach,并且由于您能够成功地控制台这些值,因此您可以获取该值并将其推送到可以添加到您的状态的变量。
axios.get(apiFilters)
.then( (response) =>{
let result=[];
response.data.forEach((req) => {
if (req.options.beauty.hair.treatment !== "0") {
req.options.beauty.hair.treatment.forEach((res) => {
if (res === valueInput) {
result.push(req);
}
})
}
})
this.setState({results:results});
})
.catch(function (error) {
console.log(error);
})
关于javascript - 使用 Axios 和 React 通过 API 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50885869/