React设置状态不会在获取成功功能中更新(在按键事件发生时)

时间:2018-11-02 15:08:37

标签: javascript reactjs fetch setstate

我有一个搜索component,其中包含一个输入,我在该输入上定义了一个key up event handler function,用于根据输入的字符串来提取数据。如您所见:

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.com/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", completed: 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;

问题是我在第二个setState中使用的.then()。响应不会更新。我想更新它并将其传递到此处导入的InstantSearchResult组件。您知道问题出在哪里吗?

编辑-添加InstantSearchResult组件

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 component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
    componentDidUpdate(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;

2 个答案:

答案 0 :(得分:2)

编辑:

请注意,setStateasynchronousthis article

我知道setState在我的fetch success上可以正常工作,问题是console.log,我不应该在setState之后使用它,而应该{{1 }}中的console.log中,我发现render()正确更新。

我不注意的另一件事是state!因此,当我InstantSearchResult Constructor re-render组件每次渲染SearchBox时,它的InstantSearchResult只运行一次。而且,如果我在constructor中使用setState,那么我将面对InstantSearchResult,因此我必须使用infinite loop来将数据传递到第二个组件。

答案 1 :(得分:1)

this已在Promise回调函数中覆盖。您将其保存到变量中:

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.com/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", completed: false }  successss

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