【问题标题】:React Native: Update FlatlistReact Native:更新平面列表
【发布时间】:2021-09-27 17:49:43
【问题描述】:

我想知道在调用我的 shuffle 函数后如何更新平面列表。我已经尝试在平面列表中使用“ExtraData”标签,但没有让它工作。任何帮助将不胜感激!

    const Display = (props) => {
    return (
      <View>
        <View style={{ flexDirection: 'row' }}>
          <Image source={props.img} style={{ width: 200, height: 200 }} />
          <Text>{props.title}</Text>
        </View>
      </View>
    );
}

function Other({ navigation }) {

  function Shuffle(array){
    let x, y, z;
    for(x = 0; x<=2;x++){
      y = Math.floor(Math.random() * 3)
      z=array[x];
      array[x] = array[y]
      array[y] = z
    } console.log(array)
  }



  let Games = [
    { title: "Tic Tac Toe", img: require("./pics/tictac.png") },
    { title: "Connect Four", img: require("./pics/ConnectFour.jpg") },
    { title: "Monopoly", img: require("./pics/mono.png") },
  ];

  return (
    <View>
      <FlatList data={Games} renderItem={({ item }) => <Display source={item} title={item.title} img={item.img}> </Display>} />
      <Button title="Shuffle" onPress={() => {Shuffle(Games)}} />
    </View>
  ); 
}

【问题讨论】:

    标签: reactjs react-native react-native-flatlist


    【解决方案1】:

    您的函数没有返回新的洗牌数组并将其分配给 Games。最佳做法是将您的数组存储在 useState 中,以便在更新时强制重新渲染并正确显示。

    const [games, setGames] = React.useState([
    { title: "Tic Tac Toe", img: require("./pics/tictac.png") },
    { title: "Connect Four", img: require("./pics/ConnectFour.jpg") },
    { title: "Monopoly", img: require("./pics/mono.png") }]);
    

    然后你的 onPress 函数可以用 Games 调用你的 shuffle 函数,返回新数组,然后用 setGames(returnedArray) 之类的东西更新

    编辑:抱歉刚刚意识到您还需要 FlatList 上的 extraData 属性来告诉它重新渲染。您希望拥有像“isShuffle”这样的状态,它将被设置为您每次调用 shuffle 函数时切换的 extraData 值。最简单的方法是在真/假之间切换,因为值本身并不重要:

    const shuffleFunc = (array) => {
    //(shuffle array and return)
    ...
    
    setGames(returnedArray);
    setIsShuffling(prev => !prev);
    

    这应该会提示 FlatList 呈现新订单。我个人通过编辑 React Native 的 FlatList 文档中的 flatlist-simple 小吃来完成这项工作。

    【讨论】:

    • 仍然无法正常工作。我在 console.log 中获得了新数组,但我不会更新 Flatlist
    • 现在添加编辑:)
    • 成功了!!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多