我正在开发一个实时搜索应用程序。我有 3 个组件。搜索、搜索栏和搜索结果。当 SearchBar 内的输入发生每次更改时,都会执行一个事件处理程序。该函数从 Search 传递到 SearchBar。 因此,每次更改时,父组件都会向服务器发送请求并获取数据。然后,父级将它们传递给子级,SearchResults 和 SearchResults 渲染它们。但问题是子组件总是落后一步
例如,我输入了 sam。 Search 将 sam 发送到服务器并收到响应。然后将它们传递给 SearchResults。但现在它正在呈现有关“sa”而不是“sam”的响应 如果我输入另一个 s 字符,我们会在搜索栏中看到 sam,但 SearchResults 会呈现获取的有关“sam”的数据。
class Search extends Component {
constructor() {
super();
this.http = new Http();
this.state = {phrase: ''};
this.searchRes = null;
}
componentDidUpdate() {
console.log('Search updated')
}
handleChange = async e => {
await this.setState({
phrase: e.target.value
});
console.log('state: '+this.state.phrase);
this.sendPhrase();
};
sendPhrase() {
return this.http.post('v1/search', {'phrase': this.state.phrase})
.then(response =>
this.searchRes = <SearchResults searchRes={response.data}/>
);
}
render() {
return (
<>
<Col xs={12}>
<SearchBar handleChange={this.handleChange} phrase={this.state.phrase}/>
</Col>
<Col xs={12}>
{this.searchRes}
</Col>
</>
);
}
}
感谢您提前关注:)
最佳答案
如果你想让组件重新渲染,你需要设置状态。像这样的行不会导致组件重新渲染:
this.searchRes = <SearchResults searchRes={response.data}/>
您设置状态的唯一时间是发生更改时,此时, this.searchRes 将设置为您上次搜索完成时设置的值。所以你总是会用最后一次渲染它。
修复方法是将结果移至状态:
constructor(props) {
super(props);
this.http = new Http();
this.state = {
phrase: '',
results: null
};
}
//...
sendPhrase() {
return this.http.post('v1/search', {'phrase': this.state.phrase})
.then(response =>
this.setState({ results: response.data })
);
}
render() {
return (
<>
<Col xs={12}>
<SearchBar handleChange={this.handleChange} phrase={this.state.phrase}/>
</Col>
<Col xs={12}>
{this.state.results && (
<SearchResults searchRes={this.state.results}/>
)}
</Col>
</>
);
}
关于javascript - 将 axios 响应传递给 React 中的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61574632/