繁体   English   中英

如何使用 axios 参数过滤 API 调用

[英]How to filter an API Call using axios parameters

我有 API 调用来显示一些成分,用户可以选择他想要过滤的成分,并且应该在同一个 Axios GET API 上触发过滤器

这是应用加载此屏幕时运行的 API 调用:

let recipeRequest = 'http://localhost:3333/report'
let ingredientsRequest = 'http://localhost:3333/ingredients'

useEffect(() => {
    recipeRequest = axios.get(recipeRequest, {params:{name:nameArr}})
    ingredientsRequest = axios.get(ingredientsRequest)
      axios.all([recipeRequest, ingredientsRequest])
        .then(axios.spread((...responses) => {
          setRecipes(responses[0].data)
          setIngredientList(responses[1].data)
        }))
        .catch(function (error) {
          console.log('API CALL - recipe/ingredient - error: ', error);
        })
  },[])

将所有数据呈现给用户,他可以选择他想要的成分,它应该过滤相应的配方。

这是包含所有 INGREDIENT 数据的平面列表

<FlatList
  horizontal
  bounces={false}
  data={ingredientList}
  renderItem={({ item, index }) => (
  <TouchableOpacity key={item.id} onPress={() => selectedIngredient(item, index)}>
    <Card key={index}>
      {item.isSelected ? (
      <>
        <Text key={item.title} style={styles.titleText}>{item.name}</Text>
        <Text style={{ color: "green" }}>{"Selected"}</Text>
      </>
      ) : (
      <>
        <Text key={item.title} style={styles.titleText}>{item.name}</Text>
        <Text style={{ color: "red" }}>{"Not Selected"}</Text>
      </>
      )}
    </Card>
    <ImageBackground key={item.illustration} source={item.illustration} style={styles.cardImage}> 
    </ImageBackground>
  </TouchableOpacity>
  )
  }
  keyExtractor={(item) => item.index}
/>

这是当用户在 flatlist 中选择成分时运行的过滤器

let obj = ingredientList.filter(field => field.isSelected === true)
const nameArr = obj.map(arr => arr.name);

更新“nameArr”后,如何在“params”中使用此“nameArr”重新调用“recipeRequest”变量以正确过滤查询?

我创建了一个名为“filteredRecipe”的函数,该函数在此屏幕中按钮的 onPress 事件中调用。 所以主要问题解决了,但现在我面临另一个问题,但这将是另一个问题,非常感谢您的帮助。

const filteredRecipe = () => {
    const filteredRecipe = recipeRequest + "?name=" + nameArr
   axios.get(filteredRecipe)
      .then((response) => {
          console.log('(response): ', response)
          setRecipes(response)
        })
        .catch(function (error) {
          console.log('API CALL - recipe/ingredient - error: ', error);
        })
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM