Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

javascript - How can I get an ID from a FlatList keyExtractor and use it in a modal?

I'm trying to take an ID from a keyExtractor in a FlatList and give that ID to a modal so that it can show the information from the API. The current implementation throws a warning - "Cannot update a component from inside the function body of a different component." The problem is that I can't think of another way to update that modal.

Here's the relevant code:

    export default function AllList() {
  const [isLoading, setLoading] = useState(true);
  const [drinkData,setDrinkData] = useState([]);
  const [searchValue, onChangeText] = useState(''); //needed for search
  const [reloading, setReloading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false); //normal modal visibility handler
  const [idDrink, setIdDrink] = useState(0);

  const renderItem = ({ item }) => {
    setIdDrink(item.id);

    return (
      <RowCard id={item.idDrink} image={item.strDrinkThumb} title={item.strDrink} alcontent={item.strAlcoholic} 
        ingredient1={item.strIngredient1} ingredient2={item.strIngredient2} ingredient3={item.strIngredient3} setModalVisible={setModalVisible}
      />
    );
  };

  useEffect (() =>  { 
    fetch('https://www.thecocktaildb.com/api/json/v1/1/search.php?s=' + searchValue)
      .then((response) => response.json())
      .then((json) => setDrinkData(json.drinks))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
      
  },[drinkData]);
  
  return (
    
    <View style = {styles.screen}>
      <View style = {styles.searchSection}>
        <TextInput 
          placeholder="Search Drinks..."  
          style={styles.input}
          onChangeText={text => onChangeText(text)}
          value={searchValue}/>
      </View>
      <FlatList
        data={drinkData}
        keyExtractor={({ idDrink }, index) => idDrink}
        removeClippedSubviews={true}
        initialNumToRender={5}
        renderItem={renderItem}
        extraData={reloading}
        
      />
      <DrinkPopup modalVisible={modalVisible} setModalVisible={setModalVisible} drinkID={idDrink}/>
      
    </View>
      
  );

};

Another user helped me get this far, but I'm on a time crunch and need to figure this out as soon as I can.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Can you try this

  keyExtractor={(item) => item. idDrink}

in flatlist drinkData is your array. so you have to pick the idDrink from every object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...