简体   繁体   中英

Setting state to empty string does not trigger a re-render for me?

I am doing a live search bar function on a table. I use an input field and tie to onKeyUp a handleChange function which sets the state with the value in the input field: the search value. This will propagate down to my table and trigger the search. It all works fine for any number of characters, and even when deleting the string as long there is still one character.

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

What doesn't work is when I delete all the characters in the input field and e.target.value gives me "". When it sets state with an empty string, it doesn't trigger a re-render at all and so my search function does not happen. I don't understand why? It's the same if I hardcoded the searchVal to be null or undefined.

Edit: Found out it does trigger a re-render in that componentWillReceiveProps and componentWillUpdate does happen, but componentDidUpdate did not, which is where I am processing the value for searching.

Edit: Turns out it does re-render, and I was doing a check for truthiness which would exclude the empty string. My bad.

Well, the problem described here, happens to me. If returned "", the state gets updated, but page does not re-render. I have made a workaround:

            if (result.file.length !== 0){
                this.setState({text: result.file})
            } else {
                this.setState({text: " "})
            }

It works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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