0

我正在尝试调度组件的 onSelect 操作以填充另一个下拉列表。我已经使用 onSelect 事件处理程序而不是 antd 的 onFieldsChange 选项来实现这一点,因为我需要使用在 onFieldsChange 回调范围内不可用的局部变量。

但结果是 - 在调用调度并重新渲染组件后,下拉元素被清除其选定值,并重置为其初始值。我无法保留选择。以下是代码片段 -

                    <FormItem {...formItemLayout} label={item.label}>
                        {getFieldDecorator(item.id, {
                           rules: [
                                { required: required, message: errorText },
                            ],
                            initialValue: initVal,
                            trigger: 'onSelect',
                        })(
                            <Select style={{ width: '100%' }} onSelect={self.handleChange.bind(self,item)}>
                                { options }
                            </Select>
                        )}
                    </FormItem>

这是 onSelect 的 handleChange 回调 -

    public handleChange(item, val) {
        console.log(item);
        console.log('Current Value: ' + val);
        let url = item.hasOwnProperty('urlOnSelect') ? item.urlOnSelect : null;
        if (!url) {
            return;
        }

        let params = item.hasOwnProperty('queryParams_S') ? item.queryParams_S : null;
        let value;

        if (params) {
            url = url + '?';
            params.map(function(param) {
                value = val;
                if (url.indexOf('?') !== (url.length - 1)) {
                    url = url + '&';
                }
                url = url + param.paramName + '=' + value;
            });
        }
        let fieldsToPopulateOnSelect = item.hasOwnProperty('fieldsToPopulateOnSelect') ? item.fieldsToPopulateOnSelect : null;
        this.props.dispatch(fetchUrlOnSelect(this.profileKey, url, fieldsToPopulateOnSelect));
        this.props.form.setFields({
            [item.id]: {
            value: val,
            },
        });
    }

注意:如上所示,我什至尝试使用 setFields 属性来设置调度后的值!但是下拉组件仍然在重新渲染时被清除!

请帮忙!!!!:|

4

2 回答 2

0

export default class UserRemoteSelect extends Component {
    static propTypes = {
      fetchType: PropTypes.string,
      token: PropTypes.string,
      defaultValue: PropTypes.object,
      onSelect: PropTypes.func,
      selectedValue: PropTypes.string
    }

    async componentDidMount () {
      this.fetchOptions()
    }

  state = {
    data: [],
    fetching: true
  };

  fetchOptions = async () => {
    if (!this.state.data.length) {
      const { fetchType, token } = this.props
      const header = { Authorization: `Bearer ${token}` }
      const route = getLocationRoute(fetchType)
      const response = await RequestObject.GetRequest(route, {}, header)
      this.setState({ data: response.data, fetching: false })
    }
  };

  render () {
    const { fetching, data } = this.state
    const { fetchType, onSelect, selectedValue } = this.props
    const id = `${fetchType}_id`
    const val = `${fetchType}_name`

    return (
      <Select
        labelInValue
        placeholder="Select Regions"
        showSearch
        notFoundContent={fetching ? <Spin size="small" /> : 'no result found'}
        filterOption={(input, option) =>
          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
        defaultValue={selectedValue}
        onChange={ onSelect }
        style={{ width: '100%' }}
      >
        {data.map(d => (
          <Option key={d[id]}>{d[val]}</Option>
        ))}
      </Select>
    )
  }
}
// Use above component in Main form like this
getFieldDecorator('parentId', {
    rules: [{ required: true, message: `Please enter ${selectFetchType} name` }],
    initialValue: ''
})(<Select 
      fetchType={selectFetchType} 
      token={ token }
      onSelect={ this.onSelect }
      selectedValue={
      { key: initialValues['selected'],
        label: initialValues['selectValue'] 
      }
    } />
)

您需要创建单独的“选择”组件,该组件从 api 和更新的选项中获取数据。例子

于 2020-06-26T08:18:51.807 回答
0

“下拉元素被清除其选定值”是指原始下拉列表还是新下拉列表(正在填充的下拉列表?)

我不认为你需要做

this.props.form.setFields({
            [item.id]: {
            value: val,
            },
        });

因为它是由 antd 处理的,所以看这个例子https://codepen.io/anon/pen/gRwyaa?editors=0010

于 2017-06-15T02:38:54.967 回答