【问题标题】:How to use hook control an array如何使用钩子控制数组
【发布时间】:2020-03-02 02:56:06
【问题描述】:

我想做一个由钩子控制的数组 看起来是这样的

 const [reasons, setReasons] = useState([false, false, false, false]);

如何使用 setReasons 切换每个布尔值

如果我喜欢这个

 onPress={() =>
        handleReasons(reasons, setReasons, number)
      }

  const handleReasons = (checked, setChecked, number) => {
    setReasons([
      ,
      {
        id: number,
        value: !reasons,
      },
    ]);
  };

它只是不工作

如果我像这样改变钩子

 const [reasons, setReasons] = useState([]);

当我调用handleReasons时,它只是在数组中添加新项目而不是更新原因[数字]值

const handleReasons = (checked, setChecked, number) => {
    setChecked([!checked[number]]);
  };

我这样改代码

它的工作原因[0] 但它无法控制数组中的其他人。

【问题讨论】:

  • 它添加了一个新项目,因为这是您使用 [...reason, ...] 分配给它的内容

标签: react-native react-hooks


【解决方案1】:
  • 您只需使用新值再次设置数组,这就是我在更新数组值时所做的。您可以console.log 值查看更新可能是视图而不是重新渲染所以只需再次调用视图渲染或使用它们的数据设置视图键

    <View key="(id) (value)" >Row data<View>
    

    代码示例

    const handleReasons = (id, newValue) => {
      let updateArray = reasons;
    
      for (let i = 0; i < updateArray.length; i++) {
        let item = updateArray[i];
        if (item.id === id) {
          item.value = newValue;
          break;
        }
      }
      setReasons(updateArray);
    };
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 2021-04-04
    • 2019-06-28
    • 2020-06-01
    • 2020-03-19
    相关资源
    最近更新 更多