反应传播运算符在嵌套状态更新上抛出错误

时间:2018-06-20 21:46:32

标签: javascript reactjs react-component spread-syntax react-state-management

我正在尝试更新我的React登录组件中的嵌套状态,以处理对登录表单字段的更改。

登录容器组件

class Login extends Component {

    constructor() {

        super();

        // define state
        this.state = {
            credentials: { 'username':'', 'password':'' },
            redirect: false
        };

        // do the binding thing that React should really just do for you
        this.handleChangeField = this.handleChangeField.bind(this);
        this.httpRequest = this.httpRequest.bind(this);
        this.renderRedirect = this.renderRedirect.bind(this);
    }

    handleChangeField(e) {

        // perform coding acrobatics to update a nested state
        const credentials = {...this.state.credentials} // !!! Unexpected token error
        credentials[ e.target.name] = e.target.value;
        this.setState({credentials})
    }

    renderRedirect(){

        if(this.state.redirect) {
          return <Redirect to='/' />
        }
    }

    httpRequest(){

        const self = this;

        axios.post('/login/',this.state.credentials).then(function(res){

            if(res.data.success){ // loggedIn = true;

                self.setState({ redirect: true })
            }

        }); 
    }

    render() {

        return (    
            <div>
                {this.renderRedirect()}
                <LoginForm 
                    handleChangeField = {this.handleChangeField} 
                    httpRequest = {this.httpRequest} 
                    state = {this.state} 
                />
            </div>
        )
    }
}

登录表单组件

const LoginForm = ({handleChangeField, httpRequest, state}) => (

    <div className="login-form block-center">

        <div className="h4 mbot10">Login</div>
        <div>
            <input type="text" name="username" placeholder="username" value={state.credentials.username} onChange={handleChangeField} className="form-control" />
            <input type="text" name="password" placeholder="password" value={state.credentials.password} onChange={handleChangeField} className="form-control" />
            <button onClick={httpRequest} >Login</button>
        </div>

    </div>
)

似乎编译器没有意识到...扩展运算符显然需要更新嵌套状态。

我发现许多解决方案都使用这种确切的语法,我在这里遗漏了什么?

社论形式的非修辞性副题:

为什么很难为嵌套对象更新状态。为什么设计React的人为什么会假设开发人员在大多数情况下会使用除嵌套对象之外的任何东西。我觉得React确实需要做得更好,以支持更新此类操作。怎么样。

this.setState({credentials[e.target.name] : e.target.value})

真的很难实施吗?

0 个答案:

没有答案