更新状态 | 对象不可迭代(无法读取属性Symbol(Symbol.iterator))

3

我有以下 JSX 代码:

 <FormGroup>
                <Label for="exampleEmail" style={{fontWeight:"bold"}}>What is your e-mail address?</Label>
                <Input type="email" name="email" id="exampleEmail" onChange={(e)=>setStateForProperties(e)} />
            </FormGroup>
            <FormGroup>
                <Label for="examplePassword" style={{fontWeight:"bold"}}>What is your password?</Label>
                <Input type="password" name="password" id="examplePassword" onChange={(e)=>setStateForProperties(e)}/>
 </FormGroup>

状态声明 -

  const iLoginCreds ={
    userName:'',
    password:''
  }
  const [loginCreds, setLoginCredentials] = useState(iLoginCreds)

onChange方法改变状态 -

  function setStateForProperties(e)
  {
    alert(e.target.id);
    switch (e.target.id) {
      case 'exampleEmail':
        setLoginCredentials(...loginCreds,{
          userName:e.target.value
        
        });
            
        break;

        case 'examplePassword':
        setLoginCredentials(... loginCreds,{
          password:e.target.value
        });
    
      default:
        break;
    }
    console.log(loginCreds);
  }

错误 -

每当我在文本框中写任何内容("onchange" 事件触发),都会收到一个错误 -

TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

enter image description here

2个回答

3
你需要在合并新对象后销毁之前的对象属性并返回一个新对象
setLoginCredentials({ ...loginCreds, ...{userName:e.target.value} })

3

不要这样做:

setLoginCredentials(...loginCreds, {
  userName:e.target.value
});

如果您向useState传递了2个参数,您应该将花括号移到环绕...loginCreds的位置,像这样:

setLoginCredentials({...loginCreds,
  userName:e.target.value
});

对于密码,你应该做同样的事情。

这只会改变对象上的一个属性。 React Hooks中的useState()与对象


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接