简体   繁体   English

React Native Selected item 未将状态反映到 UI

[英]React Native Selected item is not reflecting the state to the UI

I am trying to develop a component that should show all ingredients from my data base, but the state has not updated as expected.我正在尝试开发一个组件,它应该显示我的数据库中的所有成分,但状态没有按预期更新。

variables:变量:

  const image = require('../../assets/backgroundMeal.png');
  const [name, setName] = useState('')
  const [ingredients, setIngredients] = useState([])
  const [recipes, setRecipes] = useState([])
  const [ingredientList, setIngredientList] = useState([{id:null, name:null, isSelected:false}])

The API Call: API调用:

useEffect(() => {
    let recipeRequest = 'http://192.168.0.3:3333/report'
    let ingredientsRequest = 'http://192.168.0.3:3333/ingredients'
    recipeRequest = axios.get(recipeRequest)
    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);
          })
    
  },[ingredientList])

The variable "ingredientsRequest" has all the ingredients.变量“ingredientsRequest”包含所有成分。

This is the variable who is join the "isSelected" with the "ingredientList"这是加入“isSelected”和“ingredientList”的变量

  const [allItems, setAllItems] = useState([ingredientList]);
  const selectedIngredient = (item) => {
    let temp = allItems.filter(parentItem => parentItem.id !== item.id)
    item.isSelected = !item.isSelected;
    temp = temp.concat(item);
    temp.sort((a, b) => parseInt(a.id) - parseInt(b.id))
    
    setAllItems(temp)
    console.log('## allItems', allItems)

This is the first Problem, I declared the state with the shape "id" and "name" iguals to null and the useEffect axios call, should update the "setIngredientList" and the "ingredientList" should be updated, but the console.log that I call befor the "return" show that the Object remais with null value to the ID and NAME variable with null value.这是第一个问题,我将形状“id”和“name”iguals 的状态声明为null,并且useEffect axios 调用应该更新“setIngredientList”和“ingredientList”,但是console.log我调用之前的“返回”显示对象仍然具有空值到具有空值的 ID 和 NAME 变量。 It should be updated in the axios call I have at the useEffect, why It do not?它应该在我在 useEffect 的 axios 调用中更新,为什么不呢?

Result of the console.log at the "allItems" variable. “allItems”变量中的 console.log 结果。

Array [ Object { "id": null, "isSelected": false, "name": null, },数组 [ 对象 { "id": null, "isSelected": false, "name": null, },

Once I click in the Flatlist component, it updated the "isSelected" state correctly, but do not show all the "ingredientList" state, even considering that the "allItems" variable use the useState([ingredientList]), so I think it should have the ingredientList shape, is that right?单击 Flatlist 组件后,它会正确更新“isSelected”状态,但不会显示所有“ingredientList”状态,即使考虑到“allItems”变量使用 useState([ingredientList]),所以我认为它应该具有成分列表形状,对吗?

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

can someone help me on it?有人可以帮我吗? Thanks a lot.非常感谢。

Try this, It will reflect on UI on selection试试这个,它会在选择时反映 UI

const selectedIngredient = (item, index) => {
    const tempAllItems = [...allItems];
    tempAllItems[index].isSelected = !item.isSelected;
    
    setAllItems(tempAllItems);
}

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

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