简体   繁体   English

SetState未在React组件中触发

[英]SetState not firing in react component

I'm working on a todo app using react, redux and es2015. 我正在使用React,redux和es2015开发一个todo应用程序。 I've just introduced react-bootstrap, and my simple input control is not working as expected. 我刚刚介绍了react-bootstrap,但我的简单输入控件未按预期工作。 The code is as follows: 代码如下:

import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'
import { FormGroup, ControlLabel, Input, FormControl } from 'react-bootstrap'

class AddTodo extends React.Component {
    constructor(props) {
        super(props);

        this.handleChange = this.handleChange.bind(this);
        this.submit = this.submit.bind(this);

        this.state = {
            value: ''
        }
    }

    handleChange(e) {
        this.setState({ value: e.target.value }); // WORKS
    }

    submit() {        
        this.props.dispatch(addTodo(this.state.value)); // WORKS
        this.setState({ value: '' });  // FAILS
    }

    render() {     
        return (
            <FormGroup>
                <ControlLabel>Add Todo</ControlLabel>
                <FormControl 
                    type='text' 
                    onChange={this.handleChange}
                    onBlur={this.submit}/>           
            </FormGroup>
        );
    }
}

AddTodo = connect()(AddTodo);

export default AddTodo;

As noted in the comments above, the setState() call in the submit method which should reset the input to an empty value is not working, and the input just retains whatever was typed in last. 如上面的注释所指出的,应当将输入重置为空值的submit方法中的setState()调用不起作用,并且输入仅保留上次键入的内容。 There's no error or warning in the console either. 控制台中也没有错误或警告。

I'm obviously missing something here, but I just can't figure out what. 我显然在这里丢失了一些东西,但我只是不知道是什么。

Thanks 谢谢

Looks like your form control isn't connected to the value your keeping track of in state. 看起来您的表单控件未与您保持状态的值相关联。 Add a value attribute to your <FormControl /> 将值属性添加到您的<FormControl />

Like so: 像这样:

<FormControl 
    type='text'
    value={this.state.value}  <-- Yay value updates!
    onChange={this.handleChange}
    onBlur={this.submit}/>  

**Also going to assume the onBlur is intentional behaviour on your part. **还要假设onBlur是您的故意行为。

Grab the value first in another variable, then set the the state to '', and then dispatch: 首先在另一个变量中获取值,然后将状态设置为”,然后分派:

submit() {        
    let val = this.state.value;
    this.setState({ value: '' });  
    this.props.dispatch(addTodo(val)); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM