componentDidUpdate完成后更新组件

时间:2020-10-07 08:04:42

标签: javascript reactjs

我有一个react-autosuggest组件,该组件需要一个loading状态道具,以及来自API请求的data道具。当loading道具水合后,data状态会改变。

react-autosuggest组件中,我试图使用componentDidUpdate根据当前输入自动呈现自动建议的结果(如果更新道具时有建议)。换句话说,如果用户在loading道具更改之前(连同data道具)输入了一个值,我希望当道具更改时自动显示自动建议的结果。目前,基于onChange内置的react-autosuggest方法,直到下一次击键时,结果才会呈现。

我的父组件:

const Home = (props) => {
    const { data, loading, error } = useQuery(GET_DATA);

    if (error) return `Error! ${error.message}`;

    return (
        <HomeContainer>
            <Logo />
            <Search
                data={data ? data : null}
                home={true}
                loading={loading ? true : false}
            />
        </HomeContainer>
    );
};

Search.js的某些相关部分:

class Search extends React.Component {
    constructor() {
        super();
        this.state = {
            value: "",
            suggestions: [],
        };
        this.inputRef = React.createRef();
    }
    
    // Only try to render suggestions if loading has finished.
    getSuggestions = (value) => {
        if (!this.props.loading) {
            const inputValue = value.trim().toLowerCase();
            const inputLength = inputValue.length;
            const trie = createTrie(this.props.data, "name");
            return inputLength === 0 ? [] : trie.getMatches(inputValue);
        } else {
            return [];
        }
    };

    // I assume this is the method that is currently successfully triggering re-render
    // on input change.
    onChange = (event, { newValue }) => {
        this.setState({
            value: newValue,
        });
    };

    // If the data prop has changed and data has hydrated, set the current input value
    // to the this.value state. I need the re-render to happen after this completes,
    // and the value has been set to state. The check against the previous props prevents
    // an infinite updating loop.
    componentDidUpdate(prevProps) {
        if (
            this.props.data !== prevProps.data &&
            Object.keys(this.props.data).length
        ) {
            this.setState({
                value: this.inputRef.current.input.value,
            });
        }
    };

    render() {
        const { value, suggestions } = this.state;

        const inputProps = {
            value,
            onChange: this.onChange,
        };

        return (
                <Autosuggest
                    ref={this.inputRef}
                />
        );
    }
}

因此,除了我需要在componentDidUpdate生命周期完成后重新渲染组件这一事实之外,其他所有东西都工作正常。它将当前输入值设置为加载完成时的状态,但是仍然需要击键onChange才能重新渲染组件。

我将如何去做?

edit:为什么componentDidUpdate中的setState不触发使用新值的重​​新渲染?这就是onChange所做的全部吗?除非事件参数正在做我缺少的事情。

0 个答案:

没有答案