admin管理员组

文章数量:1422488

I have a search ponent containing an input on which I defined a key up event handler function for fetching data based on entered string. As you can see below:

class SearchBox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            timeout: 0,
            query: "",
            response: "",
            error: ""
        }
        this.doneTypingSearch = this.doneTypingSearch.bind(this);
    }
    doneTypingSearch(evt){
        var query = evt.target.value; 
        if(this.state.timeout) clearTimeout(this.state.timeout);
        this.state.timeout = setTimeout(() => {
            fetch('/?name=query' , {
                method: "GET"
            })
            .then( response => response.json() )
            .then(function(json) {
                console.log(json,"successss") 
                //Object { userId: 1, id: 1, title: "delectus aut autem", pleted: false }  successss

                this.setState({
                    query: query,
                    response: json
                })
                console.log(this.state.query , "statesssAfter" )
            }.bind(this))
            .catch(function(error){
                this.setState({
                    error: error
                })
            });
        }, 1000);
    }
  render() {
    return (
        <div>
            <input type="text" onKeyUp={evt => this.doneTypingSearch(evt)} />        
            <InstantSearchResult data={this.state.response} /> 
        </div>
        );
    }
}
export default SearchBox;

The problem is the setState which I used in the second .then(). The response won't update . I want to update it and pass it to the InstantSearchResult ponent which is imported here. Do you have any idea where the problem is ?

Edit - Add InstantSearchResult ponent

class InstantSearchBox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            magicData: ""
        }
    }
    // Both methods tried but got error =>  Maximum update depth exceeded. This can happen when a ponent repeatedly calls setState inside ponentWillUpdate or ponentDidUpdate. React limits the number of nested updates to prevent infinite loops.
    ponentDidUpdate(props) {
        this.setState({
            magicData: this.props.data
        })
    }
    shouldComponentUpdate(props) {
        this.setState({
            magicData: this.props.data
        })
    }
    render() {
        return (
            <h1>{ this.state.magicData}</h1>
        );
    }
}
export default InstantSearchBox;

I have a search ponent containing an input on which I defined a key up event handler function for fetching data based on entered string. As you can see below:

class SearchBox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            timeout: 0,
            query: "",
            response: "",
            error: ""
        }
        this.doneTypingSearch = this.doneTypingSearch.bind(this);
    }
    doneTypingSearch(evt){
        var query = evt.target.value; 
        if(this.state.timeout) clearTimeout(this.state.timeout);
        this.state.timeout = setTimeout(() => {
            fetch('https://jsonplaceholder.typicode./todos/1/?name=query' , {
                method: "GET"
            })
            .then( response => response.json() )
            .then(function(json) {
                console.log(json,"successss") 
                //Object { userId: 1, id: 1, title: "delectus aut autem", pleted: false }  successss

                this.setState({
                    query: query,
                    response: json
                })
                console.log(this.state.query , "statesssAfter" )
            }.bind(this))
            .catch(function(error){
                this.setState({
                    error: error
                })
            });
        }, 1000);
    }
  render() {
    return (
        <div>
            <input type="text" onKeyUp={evt => this.doneTypingSearch(evt)} />        
            <InstantSearchResult data={this.state.response} /> 
        </div>
        );
    }
}
export default SearchBox;

The problem is the setState which I used in the second .then(). The response won't update . I want to update it and pass it to the InstantSearchResult ponent which is imported here. Do you have any idea where the problem is ?

Edit - Add InstantSearchResult ponent

class InstantSearchBox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            magicData: ""
        }
    }
    // Both methods tried but got error =>  Maximum update depth exceeded. This can happen when a ponent repeatedly calls setState inside ponentWillUpdate or ponentDidUpdate. React limits the number of nested updates to prevent infinite loops.
    ponentDidUpdate(props) {
        this.setState({
            magicData: this.props.data
        })
    }
    shouldComponentUpdate(props) {
        this.setState({
            magicData: this.props.data
        })
    }
    render() {
        return (
            <h1>{ this.state.magicData}</h1>
        );
    }
}
export default InstantSearchBox;
Share Improve this question edited Nov 2, 2018 at 16:33 Afsanefda asked Nov 2, 2018 at 15:08 AfsanefdaAfsanefda 3,3498 gold badges42 silver badges80 bronze badges 13
  • 2 You cannot directly console.log(this.state) directly after this.setState. See the third paragraph. – Blue Commented Nov 2, 2018 at 15:11
  • 1 What returns in response? Is there a status code? Also is query on the end of your url supposed to be the value of the query variable? – Max Baldwin Commented Nov 2, 2018 at 15:11
  • query is a string the user is typed . the fetch is successfully returns some value. but the state doesn't update.Do you think the problem is with the response which I receive ? @MaxBaldwin – Afsanefda Commented Nov 2, 2018 at 15:13
  • @FrankerZ You mean the state is already updated ? But not accessible in console.log ? – Afsanefda Commented Nov 2, 2018 at 15:14
  • To piggy back off @FrankerZ, try console logging state in render rather than right after it is set. – Max Baldwin Commented Nov 2, 2018 at 15:52
 |  Show 8 more ments

2 Answers 2

Reset to default 3

Edit:

Be aware that setState is asynchronous reading this article.

I've understand that the setState works fine in my fetch success the problem was the console.log which I shouldn't use it after setState instead I console.log in render() and I found out that the state updates correctly .

The other thing I wasn't careful for was the InstantSearchResult Constructor! When I re-render the SearchBox ponent consequently the InstantSearchResult renders each time but it's constructor runs just once. And if I use setState in InstantSearchResult I will face an infinite loop so I have to use this.props instead to pass the data to the second ponent.

this has been overridden inside the promise callback function. You to save it to a variable:

doneTypingSearch(evt){
        var _this = this,
            query = evt.target.value; 
        if(this.state.timeout) clearTimeout(this.state.timeout);
        this.state.timeout = setTimeout(() => {
            fetch('https://jsonplaceholder.typicode./todos/1/?name=query' , {
                method: "GET"
            })
            .then( response => response.json() )
            .then(function(json) {
                console.log(json,"successss") 
                //Object { userId: 1, id: 1, title: "delectus aut autem", pleted: false }  successss

                _this.setState({
                    query: query,
                    response: json
                })
                console.log(_this.state.query , "statesssAfter" )
            }/*.bind(this)*/)
            .catch(function(error){
                _this.setState({
                    error: error
                })
            });
        }, 1000);
    }

本文标签: javascriptReact setstate doesn39t update in fetch success function (on key up event)Stack Overflow