antdesign模态框+穿梭框闪现问题

闪现原因

onchange时的setState导致重新渲染

handleChange = (targetKeys) => {
    this.setState({ targetKeys }); 
  }
解决方法

把Modal单独抽离到一个组件中,将Modal的显示隐藏(visible)放到了子组件中

// 新建TransferModal
import React, { Component } from 'react';
import { Modal,Transfer } from 'antd';

class TransferModal extends Component {

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  showModelHandler = (e) => {
    if (e) e.stopPropagation();
    this.setState({
      visible: true,
    });
  };

  hideModelHandler = () => {
    this.setState({
      visible: false,
    });
  };

  okHandler = () => {
    this.setState({
      visible: false,
    });
  }

  filterOption = (inputValue, option) => {
    return option.description.indexOf(inputValue) > -1;
  };

  handleChange = (targetKeys) => {
    this.props.changeTargetKeys(targetKeys)
  };

  render() {
    const { children } = this.props;
    return (
      <span>
        <span onClick={this.showModelHandler}>
          { children }
        </span>
        <Modal
          title={this.props.title}
          visible={this.state.visible}
          onOk={this.okHandler}
          onCancel={this.hideModelHandler}
        >
          <Transfer
            titles={['可加入的组','已选择的组']}
            dataSource={this.props.dataSource}
            showSearch
            filterOption={this.filterOption}
            targetKeys={this.props.targetKeys}
            onChange={this.handleChange}
            render={item => item.name}
          />
        </Modal>
      </span>
    );
  }
}

export default TransferModal;

父组件异步获取数据,修改state,TransferModal中穿梭框的onchange传回父组件进行处理。

//父组件中获取数据
  getGroupData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'listGroup/fetch',
    }).then((data) => {  //这里需要在effects中return一下,才能拿到回调
      this.setState({ groupData:data.data.list })
    });
  };

  handleGroupModalChange = (targetKeys) => {
    this.setState({ targetKeys });
  };
<TransferModal
  dataSource={this.state.groupData}
  filterOption={this.filterOption}
  targetKeys={this.state.targetKeys}
  changeTargetKeys={(targetKeys) => this.handleGroupModalChange(targetKeys)}
  title="加入组"
>
  <a>加入群组</a>
</TransferModal>

model文件中effects的return

effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryGroup, payload);
      yield put({
        type: 'save',
        payload: response,
      });
      return {
        data: response,
      };
    },
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容