React 设置状态不会在获取成功函数中更新(在按键事件中)
React set-state doesn't update in fetch success function (on key up event)
我有一个搜索 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;
问题是我在第二个 .then()
中使用的 setState
。响应不会更新。我想更新它并将其传递给此处导入的 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;
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);
}
编辑:
请注意 setState
是 asynchronous
阅读 this article。
我知道 setState
在我的 fetch success
中工作正常问题是 console.log
我不应该在 setState
之后使用它而是我 console.log
在 render()
中,我发现 state
更新正确。
我没注意的另一件事是 InstantSearchResult Constructor
!当我 re-render
SearchBox
组件因此 InstantSearchResult
每次都呈现,但 constructor
只运行一次。如果我在 InstantSearchResult
中使用 setState
,我将面临 infinite loop
,所以我必须使用 this.props
来将数据传递给第二个组件。
我有一个搜索 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;
问题是我在第二个 .then()
中使用的 setState
。响应不会更新。我想更新它并将其传递给此处导入的 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;
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);
}
编辑:
请注意 setState
是 asynchronous
阅读 this article。
我知道 setState
在我的 fetch success
中工作正常问题是 console.log
我不应该在 setState
之后使用它而是我 console.log
在 render()
中,我发现 state
更新正确。
我没注意的另一件事是 InstantSearchResult Constructor
!当我 re-render
SearchBox
组件因此 InstantSearchResult
每次都呈现,但 constructor
只运行一次。如果我在 InstantSearchResult
中使用 setState
,我将面临 infinite loop
,所以我必须使用 this.props
来将数据传递给第二个组件。