【问题标题】:HandleChange/setState stopped working after migrating to react useState hookHandleChange/setState 在迁移以响应 useState 挂钩后停止工作
【发布时间】:2020-11-14 13:13:12
【问题描述】:

我有一个使用 classBased react 的组件,它工作正常,我决定切换到 usestate 并且它停止工作。现在handlechange以随机方式记录状态,但是不能正常工作

我的handlechange和useState

  const [state, setState] = useState({
    email: "",
    password: "",
    wrongCombo: false,
    serverError: false
})

const handleChange = (evt) => {
    const target = evt.target;
    const value = target.value;
    const name = target.name;
    console.log(name)
    console.log(value)
    setState({
        [name]: value
    });
}

我的handlesubmit(它检测到console.log中的随机值,找不到逻辑,但日志不会根据handlechange中的输入获得这两个值)

const handleSubmit = (event) => {
        event.preventDefault();

        const { email, password } = state;
        console.log(state)
        props.login(email, password, "login").
            then(data => {
            }).catch((err) => {
                if (err == "Error: Request failed with status code 403") {
                    setState({
                        wrongCombo: true
                    }, () => {

                    })
                } else if (err == "Network error") {
                    setState({
                        serverError: true
                    })
                }
            })
    }

这是我的渲染

<div>
            <form>
                {state.wrongCombo ? <Alert variant="danger" dismissible onClose={handleDismiss}> Wrong email and password combination </Alert> : null}
                {state.serverError ? <Alert variant="danger" dismissible onClose={handleDismiss}> Server Error </Alert> : null}
                <div class="form-group">
                    <label for="exampleInputEmail1">Email address</label>
                    <input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" onChange={handleChange} />
                </div>
                <div class="form-group">
                    <label for="exampleInputPassword1">Password</label>
                    <input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password" onChange={handleChange} />
                </div>
                <div className="text-center buttonContainer">
                    <button type="submit" class="btn btn-primary buttonLogin" onClick={handleSubmit}>Submit</button>
                </div>
            </form>
        </div>

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    来自docs on useState:

    与类中的 this.setState 不同,更新状态变量总是替换它而不是合并它。

    更新时必须替换 useState 对象中的所有值。您仅使用 一个 键向更新程序提供对象,因此只会保留该键。

    这样做的一个简单模式是在传递更新之前传播先前的状态:

    setState(prev => ({...prev, [newKey]: newVal }));
    

    【讨论】:

    猜你喜欢
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 2021-06-16
    • 2010-12-21
    相关资源
    最近更新 更多