【问题标题】:How to filter an API Call using axios parameters如何使用 axios 参数过滤 API 调用
【发布时间】:2021-02-20 22:03:03
【问题描述】:

我有 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);
        })
  },[])

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

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

<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}
/>

这是当用户在平面列表中选择一种成分时运行的过滤器

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

一旦“nameArr”被更新,如何在“params”中重新调用带有这个“nameArr”的“recipeRequest”变量以使查询正确过滤?

【问题讨论】:

    标签: javascript node.js rest axios


    【解决方案1】:

    我创建了一个名为“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);
            })
      }
    

    【讨论】:

      猜你喜欢
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 2021-12-26
      • 2020-01-11
      • 1970-01-01
      • 2021-10-13
      • 2020-06-05
      相关资源
      最近更新 更多