简体   繁体   English

如何在React中重置状态以便视图更新

[英]How to reset State in React so the view updates

I am trying to reset a input field on state update. 我正在尝试重置状态更新的输入字段。 So when my state updates through a function my view would change as well. 因此,当我的状态通过函数更新时,我的视图也会改变。 Below is my code: 下面是我的代码:

constructor(props){
    super(props)
    this.state = { song: '',
                   videos: '' }
    this.handleSongInput = this.handleSongInput.bind(this)
}

in my render function I do something like this 在我的渲染功能中,我做了这样的事情

render () {
    return (
            <div>
                <TextField
                  floatingLabelText="Search Songs"
                  value={this.state.value}
                  onChange={this.handleSongInput}
                />
                <br />
                <RaisedButton label="Search" onClick={this.searchSong} />
            </div>
    )
}

The handle function for the Input field is below. 输入字段的句柄功能如下。 It is simply setting the state. 它只是在设置状态。

handleSongInput = (e) => {
        this.setState({ song: e.target.value})
    }

Now on button click I have the following function which resets the initial 现在单击按钮,我有以下功能可以重置初始

searchSong = () => {
        ...
        this.setState({song:''})
    }

Now if I do a console.log I can see that the state has changed. 现在,如果我执行console.log,则可以看到状态已更改。 But in my view I can still see that the text field is populated with previous text. 但是在我看来,我仍然可以看到该文本字段中填充了以前的文本。 在此处输入图片说明

How can I set the value of textfield with current state 如何设置当前状态的文本字段的值

I believe you have a variable name issue: 我相信您有一个变量名问题:

value={this.state.value}

should read: 应该读:

value={this.state.song}

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

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