【发布时间】:2019-10-09 01:37:38
【问题描述】:
我有一个输入字段,应该在输入和发出搜索请求时使用一些延迟选项。每当道具中的搜索文本发生变化时,我还需要重新运行此搜索组件。但是我遇到了一个问题,在粘贴无法找到的值并尝试将其删除后,搜索字段挂起。
export class TableToolbar extends Component {
state = {
search: this.props.search,
}
static getDerivedStateFromProps(props, state) {
// Re-run the table whenever the search text change.
// we need to store prevSearch to detect changes.
if (props.search !== state.prevSearch) {
return {
search: props.search,
prevSearch: state.search,
}
}
return null
}
captureInput = e => {
if (this.timer) {
clearTimeout(this.timer)
delete this.timer
}
this.input = e.target.value
this.setState({search: this.input})
this.timer = setTimeout(() => {
this.props.handleSearch(this.input)
delete this.input
}, capturedInputTimeout)
}
render() {
<input onChange={this.captureInput} value={this.state.search} />
}
}
我还找到了另一种解决方案,用use-debounce https://github.com/xnimorz/use-debounce 消除这个handleSearch 请求
但仍然不太了解如何正确重新渲染组件。 在某些情况下,当我想在页面之间移动时保留搜索值时,我需要从父级传递搜索道具。
use-debounce 的第二个变体,但仍然不太明白如何在搜索道具更新时重新渲染组件
const TableToolbar = ({search, handleSearch}) => {
const [searchValue, setSearchValue] = useState(search)
const [debouncedText] = useDebounce(searchValue, 500)
useEffect(() => {
handleSearch(debouncedText)
},
[debouncedText]
)
render() {
<input onChange={e => setSearchValue(e.target.value)} />
}
}
【问题讨论】:
标签: javascript reactjs