簡體   English   中英

為什么當我刪除搜索字段中的輸入過快時結果不會消失? (Javascript)

[英]Why the results don't disappear when I delete too fast the input in the search field? (Javascript)

我有一個映射 state 的輸入字段並向我顯示更改的結果:

if (this.state.results === "" || this.state.results === null || this.state.results === undefined){
            showResults = null;
        } else {
            let results = this.state.results.map(result => (
                <StyledLink key={result.name} to={`/game/${result.name}`}> 
                    <SearchResult
                        name={result.name}
                    />
                </StyledLink>)
            )

            showResults = <StyledResults>{results}</StyledResults>
        }

一切正常,但是當我按下刪除按鈕快速時,即使輸入字段為空,它仍然會顯示結果。 如果我在每次刪除按下之間等待半秒,它就不會發生。

這就是輸入字段觸發 onChange 的原因:

findGames = (event) => {
    let searchText = event.target.value
    if (event.target.value) {
        let body = {
            "search_text": `${searchText}`, "fields": ["id", "name", "release_dates"]
        }
        axios.post(getGameIDUrl, body, headers)
            .then(res => res.data.filter((result) => { return result.type === "game" }))
            .then(res => this.setState({ results: res }))
            .then(console.log(this.state.results))
    } else {
        this.setState({ results: null })
    }


}

在發送另一個請求之前,您必須取消之前axios.post請求。 如果您完全刪除搜索詞, this.setState({ results: null })會立即調用,但之前的請求仍在途中,當他們回來時,他們將 state 設置為不想要的結果。

以下是如何取消請求的示例:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

您需要取消請求,否則無論何時返回請求,您都將設置 state。

初始化 state 並將其重置為空數組[]而不是null也可能有所幫助

const CancelToken = axios.CancelToken;
let cancel;

class SomeComponent extends React.Component {
    state = {
        values:'',
        results:[]
    }
    findGames = (event) => {
        if(cancel){
            cancel()
            console.log('request canceled')
        }
        setState({ value:event.target.value, results:[]})

        if(event.target.value === ''){
                return null
        }

        const getGameIDUrl = 'www.someapi.com/api'
        const body = { "search_text": `${event.target.value}`, "fields": ["id", "name", "release_dates"]}
        const headers = {Authorization:'bearer API_TOKEN'}

        axios.post(
            getGameIDUrl, 
            body, 
            {cancelToken: new CancelToken((c)=> cancel = c)},
            headers
        ).then(res =>{
            const results = res.data.filter((result) => result.type === "game" )
            this.setState({ results })
        })
    }

    render(){
        console.log(this.state.results)

        return (
            <div>
                <input onChange={this.findGames} value={this.state.value} />
                <StyledResults>
                    {this.state.results.map(result => (
                        <StyledLink key={result.name} to={`/game/${result.name}`}> 
                            <SearchResult
                                name={result.name}
                            />
                        </StyledLink>
                    ))}
                </StyledResults>
            </div>
            )
    }
} 

暫無
暫無

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

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