简体   繁体   English

在React中调用this.setState({term:''})之后,输入值未重新呈现

[英]Input value not being re-rendered after calling this.setState({ term: ' ' }) in react

I am following a react tutorial and trying to re-render the value of a form input field after the user submits the form. 我正在关注一个React教程,并在用户提交表单后尝试重新呈现表单input字段的值。 However, the value in the input remains in a previous state despite updating the state as shown below. 但是,尽管更新了状态, input的值仍保持先前的状态,如下所示。

    constructor(props){
        super(props);
        this.state = { term: '' };
        this.onInputChange = this.onInputChange.bind(this);
        this.onFormSubmit = this.onFormSubmit.bind(this);
    }
    render(){
        return(
            <form onSubmit={this.onFormSubmit} className="input-group">
                <input
                    placeholder="Search Days Forecast"
                    className="form-control"
                    value={this.state.value}
                    onChange={this.onInputChange}
                />
                <span className="input-group-btn">
                    <button type="submit" className="btn btn-secondary"> Submit </button>
                </span>
            </form>
        );
    }

    onInputChange(event){
        this.setState({term: event.target.value});
    }
    onFormSubmit(event){
        event.preventDefault();
        this.props.fetchWeather(this.state.term);
        this.setState({ term: '' });
    }
}function mapDispatchToProps(dispatch){
        return bindActionCreators({ fetchWeather }, dispatch);
    }
export default connect(null, mapDispatchToProps)(SearchBar);

fetchWeather is just a function that sends a get request. fetchWeather只是一个发送获取请求的函数。 Any help on why the value field is not re-rendering with the new state will be highly appreciated. 我们将非常感谢您对为何不使用新状态重新渲染值字段的任何帮助。

try this 尝试这个

           <input
                placeholder="Search Days Forecast"
                className="form-control"
                value={this.state.term}
                onChange={this.onInputChange}
            />

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

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