为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

绝地无双 2022-08-27 09:20:29
我在 React Native 中有一个 signUp 组件(没有 expo),它可能有多个电子邮件输入,每个组件后面都有一个 Switch 组件,指示这是否是主要电子邮件。我正在使用 react useState 来管理字段列表的行为。但是当我按下开关来切换主属性的值时,Switch卡住了,直到我执行下一个操作才移动(在此示例中,我创建了一个按钮,在数组上插入一个新项,并制作了另一个虚拟工作开关)。但是如果我打印该值,它将按预期正常切换,但组件本身不会立即响应。这是我到目前为止的代码: 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>    </>  );}任何帮助将不胜感激!
查看完整描述

1 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

您只需要通过像这样分散以前的数组来创建新数组


const setMainEmail = (value, emailIndex) => {

    const array = [...emails];

    console.log(array);

    array[emailIndex].main = value;

    console.log(array);

    setEmails(array);

  };

这是另一个方案工作和失败的原因,你在添加新项的方案中做对了。


查看完整回答
反对 回复 2022-08-27
  • 1 回答
  • 0 关注
  • 204 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号