如何在 React 或 React Native 中将项目添加到列表并按 属性 排序

How to add items to a list and order by property in React or React Native

我希望将我的 json 数据放在一个列表中,然后将对象添加到列表中并按位置对所有内容进行排序

const [list, setList] = useState([])

const blocks = 4

const placeholder = [{ action : null, location : null, title : null }]

const json = [
  {
    "action": "go back",
    "location": 0,
    "title": "first Demo"
  },
  {
    "action": "press go",
    "location": 2,
    "title": "Second"
  }
]

Output I am hoping for when I console.log(list)

[
  {
    "action": "go back",
    "location": 0,
    "title": "first Demo"
  },
  {
    "action": "none",
    "location": 1,
    "title": "first Demo"
  }, 
  {
    "action": "press go",
    "location": 2,
    "title": "Second"
  },
  {
    "action": "none",
    "location": 3,
    "title": "first Demo"
  }
]

我试过的。它有效,但想要更好的方法来做到这一点

const jsonValue = await AsyncStorage.getItem('@custom_layout');
      if (jsonValue != null) {
        const createPallet = Array.from({length: blocks}, (v, i) => ({
          title: null,
          icon: null,
          UUID: i,
          location: i,
          Children: [],
          action: null,
        }));

        JSON.parse(jsonValue).map((item, i) => {
          //Find index of specific object using findIndex method.
          const objIndex = createPallet.findIndex(
            obj => obj.location === item.location,
          );

          //Update object's.
          createPallet[objIndex] = item;

          // This will update your state and re-render
          setItems([...createPallet]);
        });

基本上我们得到了块的计数。然后我们按位置重新排序 json。如果 0-3 之间存在差距,请用占位符数据填充它

设置变量列表的位置 const [list, setList] = useState([]) 你实际上是将它设置为一个空数组 []。但这只是关于术语的一点。您可以使用排序函数对数组进行排序,如下所示。但请耐心等待,我要将其重命名为数组。

const [array, setArray] = useState([]);

//Now you can add missing blocks.
for(let i=0; i<blocks; i++){
   if(!json.find(element=>element.location==i)){
      const newplaceholder = placeholder[0];
      newplaceholder.location = i;
      json.push(newplaceholder)
   }
}


//This is your sort function
const sortArray = (a, b)=>{
   return a.location-b.location
}

//When you want to use it to sort the array
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
json.sort(sortArray)

//Once you've added the placeholders and sorted the array
setArray(json);