gpt4 book ai didi

reactjs - 根据 redux 和 React 中的状态来限制 HTTP 调用的正确方法

转载 作者:行者123 更新时间:2023-12-03 13:18:59 26 4
gpt4 key购买 nike

我需要什么:一个controlled component这是一个输入[type="search"]。比如说,在该组件 1 秒内没有任何更改之后,我想发送一个 HTTP 调用来执行该搜索,并将结果显示在另一个组件中。

我是如何做到的:每当我调用 dispatch(setSearch(str)); 时,我都会调用 dispatch(displaySearch(false)); 然后调用 _.throttle调用 dispatch(displaySearch(true));

我觉得在组件中做这种工作是不正确的,但我想不出在 redux 的 reducer 中做到这一点的方法。

最佳答案

您有不同的选择来解决这个问题。

<强>1。在组件级别对您的操作进行反跳

这是最简单的方法。当输入触发变化时,它会调用setSearch 的去抖版本延迟了服务器调用。

import * as React from "react"
import {connect} from "react-redux"
import {setSearch} from "./actions"

export default connect(
null,
function mapDispatchToProps(dispatch) {
const setSearch_ = _.debounce(q => dispatch(setSearch(q)), 1000)
return () => ({setSearch: setSearch_})
}
)(
function SearchForm(props) {
const {setSearch} = props
return (
<input type="search" onChange={setSearch} />
)
}
)

<强>2。使用 redux-saga 去抖动

这种方法需要更多样板文件,但可以让您更好地控制工作流程。使用 saga 我们拦截 SET_SEARCH 操作,对其进行反跳,调用 API,然后分派(dispatch)包含结果的新操作。

import {call, cancel, fork, put, take} from "redux-saga/effects"
import {setSearchResults} from "./actions"
import {api} from "./services"
import {delay} from "./utils"

export default function* searchSaga() {
yield [
// Start a watcher to handle search workflow
fork(watchSearch)
]
}

function* watchSearch() {
let task

// Start a worker listening for `SET_SEARCH` actions.
while (true) {
// Read the query from the action
const {q} = yield take("SET_SEARCH")

// If there is any pending search task then cancel it
if (task) {
yield cancel(task)
}

// Create a worker to proceed search
task = yield fork(handleSearch, q)
}
}

function* handleSearch(q) {
// Debounce by 1s. This will lock the process for one second before
// performing its logic. Since the process is blocked, it can be cancelled
// by `watchSearch` if there are any other actions.
yield call(delay, 1000)

// This is basically `api.doSearch(q)`. The call should return a `Promise`
// that will resolve the server response.
const results = yield call(api.doSearch, q)

// Dispatch an action to notify the UI
yield put(setSearchResults(results))
}

关于reactjs - 根据 redux 和 React 中的状态来限制 HTTP 调用的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36602534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com