繁体   English   中英

在父道具改变时重新输入反应组件

[英]Rerender input react component on parent props change

我在输入字段中应该在键入和发出搜索请求时使用一些延迟选项。 此外,每当搜索文本更改为道具时,我都需要重新运行此搜索组件。 但是我遇到了一个问题,并且在粘贴无法找到的值并尝试删除它之后,搜索字段会挂起。

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 handleSearch去抖动这个handleSearch请求的解决方案https://github.com/xnimorz/use-debounce

但仍然不太明白如何正确地重新渲染组件。 在某些情况下,当我想在页面之间移动时保持搜索值时,我需要从父级传递搜索道具。

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

对于挂起的问题,我认为你的captureInput函数在每次重新渲染时运行。 您应该像这样调用它来避免onChange={() => this.captureInput

对于重新渲染变化,您可以查看shouldComponentUpdate ,其中您已经接受了nextProps ,您可以将其与当前道具进行比较,如果不同则返回true。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM