【问题标题】:Rerender input react component on parent props change在父道具更改上重新渲染输入反应组件
【发布时间】: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


    【解决方案1】:

    对于挂起的问题,我认为您的 captureInput 函数在每次重新渲染时都会运行。你应该这样称呼它以避免onChange={() =&gt; this.captureInput

    对于更改的重新渲染,您可以查看shouldComponentUpdate,在那里您可以访问nextProps,您可以将其与当前道具进行比较,如果不同则返回true。

    【讨论】:

    • 它不会在每次重新渲染时运行,因为我使用 onChange={this.captureInput} 而不是 onChagne={this.captureInput()}
    • 此外,当我删除 getDerivedStateFromProps 时,除了更新道具更改上的组件外,一切正常
    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 2020-05-01
    • 2021-01-22
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多