簡體   English   中英

將 axios 響應傳遞給反應中的子組件

[英]passing axios response to child component in react

我正在開發一個實時搜索應用程序。 我有 3 個組件。 搜索、搜索欄和搜索結果。 在 SearchBar 內的每次輸入更改時,都會執行一個事件處理程序。 這個 function 從 Search 傳遞到 SearchBar。 每次更改時,父組件都會向服務器發送請求並獲取數據。 然后,父母將它們傳遞給它的孩子,SearchResults 和 SearchResults 呈現它們。 但問題是子組件總是落后一步

例如,我輸入了 sam。 搜索將 sam 發送到服務器並收到響應。 然后將它們傳遞給 SearchResults。 但現在如果我輸入另一個 s char,它會呈現關於“sa”而不是“sam”的響應,我們在搜索欄中有 sams,但 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>
        </>
    );
}
}

我提前感謝您的關注:)

如果要重新渲染組件,則需要設置 state。 像這樣的行不會導致組件重新渲染:

this.searchRes = <SearchResults searchRes={response.data}/>

您設置 state 的唯一時間是發生更改時,此時, this.searchRes 設置為您在上次完成搜索時設置的任何內容。 所以你總是會在最后一次渲染它。

修復方法是將結果移動到 state 中:

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>
        </>
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM