通过在 React Native 上切换 Switch 组件来更新数组状态中的值

Updating a value inside an array state through toggling a Switch Component on React Native

我在 React Native(没有 expo)中有一个 signUp 组件,它可以有多个电子邮件输入,每个输入后跟一个 Switch 组件,指示这是否是主要电子邮件。我正在使用 React useState 来管理字段列表的行为。但是当我按下开关切换主要属性的值时,开关卡住并且不会移动,直到我执行下一个操作(在这个例子中,我创建了一个按钮,用于在数组中插入一个新项目并使另一个虚拟工作转变)。但是如果我打印该值,它会按预期正常切换,但组件本身不会立即响应。到目前为止,这是我的代码:

 import React, {useState} from 'react';
import {TextInput, View, Text, Switch, Button} from 'react-native';

export default function Signup() {
  const [isEnabled, setIsEnabled] = useState(false);
  const [emails, setEmails] = useState([
    {
      email: '',
      main: true,
    },
  ]);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);
  const setMainEmail = (value, emailIndex) => {
    const array = emails;
    console.log(array);
    array[emailIndex].main = value;
    console.log(array);
    setEmails(array);
  };
  const addNewEmail = () => {
    setEmails([
      ...emails,
      {
        email: '',
        principal: false,
      },
    ]);
  };
  return (
    <>
      <View>
        <Text>Dummy Switch That Works</Text>
        <Switch
          trackColor={{false: '#767577', true: '#767577'}}
          thumbColor={isEnabled ? '#FD7E77' : '#f4f3f4'}
          ios_backgroundColor="#3e3e3e"
          onValueChange={toggleSwitch}
          value={isEnabled}
        />
      </View>
      <View>
        {emails.map((email, emailIndex) => (
          <View key={emailIndex}>
            <TextInput
              placeholder="Email"
              autoCapitalize="none"
              keyboardType="email-address"
            />
            <View>
              <Switch
                value={email.main}
                trackColor={{false: '#767577', true: '#767577'}}
                thumbColor={email.main ? '#FD7E77' : '#f4f3f4'}
                ios_backgroundColor="#3e3e3e"
                onValueChange={event => setMainEmail(event, emailIndex)}
              />
              <Text color="#fff">Main?</Text>
            </View>
          </View>
        ))}
        <Button onPress={addNewEmail} title="+ Email" />
      </View>
    </>
  );
}

任何帮助将不胜感激!

你只需要像这样展开之前的数组来创建一个新数组

const setMainEmail = (value, emailIndex) => {
    const array = [...emails];
    console.log(array);
    array[emailIndex].main = value;
    console.log(array);
    setEmails(array);
  };

这就是另一个方案起作用而这个方案失败的原因,您在添加新项目的方案中做得对。