在父道具更改时渲染输入反应组件

时间:2019-05-22 14:17:03

标签: javascript reactjs

我在输入字段中输入和提出搜索请求时应使用一些延迟选项。每当搜索文本在道具中更改时,我还需要重新运行此搜索组件。但是我遇到了一个问题,在粘贴找不到的值并尝试将其删除后,“搜索”字段挂起。

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

}

我还找到了另一种解决方案,可以用handleSearch https://github.com/xnimorz/use-debounce

对这个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)}  />
        }
    }

1 个答案:

答案 0 :(得分:0)

对于挂起问题,我认为您的captureInput函数在每次重新渲染时都运行。您应该这样称呼它以避免MongoDB

要重新呈现更改,您可以查看onChange={() => this.captureInput所在的shouldComponentUpdate,您可以将其与当前道具进行比较,如果不同则返回true。

相关问题