【问题标题】:Updating State | object is not iterable (cannot read property Symbol(Symbol.iterator))更新状态 |对象不可迭代(无法读取属性 Symbol(Symbol.iterator))
【发布时间】:2021-10-09 03:18:47
【问题描述】:

我有下面的 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))

【问题讨论】:

    标签: javascript reactjs state


    【解决方案1】:

    您需要destruct previous object properties 并在与新的合并后返回new object

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

    【讨论】:

      【解决方案2】:

      不要这样做:

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

      ,将 2 个参数传递给 useState,您应该将花括号移动到包围 ...loginCreds,如下所示:

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

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

      这只会改变对象的一个​​属性。 React Hooks useState() with Object

      【讨论】:

        猜你喜欢
        • 2019-10-09
        • 2020-09-06
        • 2021-02-20
        • 2021-04-28
        • 2022-06-14
        • 2017-11-03
        • 1970-01-01
        • 1970-01-01
        • 2020-11-30
        相关资源
        最近更新 更多