如何使用 setWayPoints() 而不是 wayPoints.splice 将对象添加到特定位置的数组中? (使用反冲状态)

How to add objects into array on specific position with setWayPoints() instead of wayPoints.splice? (useRecoilState)

我目前有一个带对象的反冲全局状态数组(默认值:开始和目的地),我想在它们之间添加 Waypoints。按下绿色加号按钮后,新的 Waypoints 出现在 Start 和 Destination 之间:

我的问题是,它不会在单击“添加”按钮时立即出现,但只有在我触发任何其他 useState 时才会出现。可能是因为我没有将 waypoints 添加到数组中:“setWayPoints()”,而是“wayPoints.splice”。有什么方法可以使用“setWayPoints()”将它们添加到数组中吗?

将Waypoints添加到全局状态数组的代码:

<MaterialCommunityIcons
      selectable={selectable}
      style={styles.addIcon}
      name="plus-circle"
      size={30}
      color={"green"}
      onPress={() => {
        wayPoints.splice(key + 1, 0, {
            coordinates: { longitude: 0, latitude: 0 },
            place: "",
            placeholder:
              key === wayPoints.length - 1
                ? "Destination"
                : "Waypoint",
       })
      console.log(wayPoints);
    }}
 /> 

如果您需要任何进一步的信息,请随时询问!

提前致谢!

试试这个?

wayPoints.splice…
setWaypoints(wayPoints)

我通过替换解决了问题:

onPress={() => {
        wayPoints.splice(key + 1, 0, {
            coordinates: { longitude: 0, latitude: 0 },
            place: "",
            placeholder:
              key === wayPoints.length - 1
                ? "Destination"
                : "Waypoint",
       })

与:

onPress={() => {
        let old = [...wayPoints];
        old.splice(key + 1, 0, {
           coordinates: { longitude: 0, latitude: 0 },
           place: "",
           placeholder:
           key === wayPoints.length - 1
             ? "Destination"
             : "Waypoint",
        });
        setWayPoints(old);
       }}

这是一个简单的代码,允许您在当前项目的索引之前或之后将项目添加到数组

export const arrayAddItem = ({array, itemValue, index, position = 'after'}) => {
    const increasingCoeff = position === 'after' ? 1 : 0;
    return [
        ...array.slice(0, index + increasingCoeff),
        itemValue,
        ...array.slice(index + increasingCoeff)
    ];
};

示例:

const data = [
 {
  name: 'Yoda'
 },
 {
 name: 'Luke'
 },
 {
 name: 'Vader'
 }
]

console.log(arrayAddItem({
  array: data,
  itemValue: {name: 'Lea'},
  index: 1, // an index, after (or before) of which we add a new item to array
  // position is optional and default is 'after', but you can also add an items 'before' the specified index.
}))

结果应该是

[
 {
  name: 'Yoda'
 },
 {
 name: 'Luke'
 },
 {
 name: 'Lea'
 },
 {
 name: 'Vader'
 }
] 

或者如果您需要向特定索引添加新值,请使用此代码:

export const arraySetValueByIndex = ({array, itemValue, index}) => {

    const startPart = array.slice(0, index);
    const endPart = array.slice(index + 1);
    return [
        ...startPart,
        itemValue,
        ...endPart
    ];
};