传递新道具时重置“反应选择”下拉菜单

时间:2020-03-17 12:38:13

标签: reactjs react-select

我想清除下拉菜单中获取新道具的价值。当前,即使我扩大了下拉菜单,我仍然可以看到新的值。

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;

我已确认setState()内第一个清除componentDidUpdate的{​​{1}}会调用optionList

编辑:这是codesandbox

1 个答案:

答案 0 :(得分:0)

您忘记在Select组件上显式设置一个值。您必须将this.state.selectedKeydate中的KeydateDropdown传递给MainInputBar,然后将该值传递给Select组件:

MainInputBar.jsx中:

      keydateDropdown = (
        <KeydateDropdown
          vesselname={this.state.selectedVessel.value}
          selectedKeydate={this.state.selectedKeydate}
          handleKeydateChange={this.handleKeydateChange}
          value={this.state.selectedKeydate}
        />
      );

KeyStateDropdown.jsx中:

      <Select
        isDisabled={this.props.isDisabled}
        onChange={this.props.handleKeydateChange}
        options={this.state.optionList}
        className={styles.dropdown}
        value={this.props.value}
      />

我分叉了您的沙箱,并将其固定在此处:https://codesandbox.io/s/happy-einstein-55klv