触发2次在道具变更时重新渲染

时间:2020-03-12 12:29:39

标签: reactjs

我想在选择vesselname时返回空选项。使用以下代码,将optionList更新为componentDidUpdate内的空数组不会触发重新渲染。因此,在选择新容器时,将保留先前的关键日期,尽管如果单击下拉列表,则可以看到它使用api调用中的新值填充。

KeydateDropdown.js

import React from 'react';
import Select from 'react-select';
import axios from 'axios';    

class KeydateDropdown extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            optionList: []
        };
    };

    componentDidUpdate(prevProps) {
        let vesselname = this.props.vesselname;
        if (prevProps.vesselname !== vesselname) {
            let keydateList = [];
            this.setState({
                optionList: keydateList
            });
            axios.get('list-keydates', {
                params: {
                    vesselname: vesselname
                }
            })
                .then((response) => {
                    let data = response.data['intervention'];
                    data.forEach((element) => {
                        keydateList.push({ value: element, label: element });
                    });
                    this.setState({ optionList: keydateList });
                })
        }
    }


    render() {

        return (
            <Select
                isDisabled={this.props.isDisabled}
                onChange={this.props.handleKeydateChange}
                options={this.state.optionList}
                className={styles.dropdown}
            />
        );
    }

}

export default KeydateDropdown;

1 个答案:

答案 0 :(得分:0)

使用

componentWillUpdate(nextProps)

componentDidUpdate(prevProps, prevState)