微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

下拉清除但组件更新后状态保持不变

如何解决下拉清除但组件更新后状态保持不变

我一直在关注一些关于使用 fluent ui 和 React 创建 SPFX webpart 表单的tutorials

我的 webpart 组件构造如下:

 constructor(props: IOrderingProps,wpState: ICurrentWpState) {
    super(props);
    // init the state properties
    this.state = {
      companyDropDownSelected: "",cart: null
    };

    this.showStateClicked = this.showStateClicked.bind(this);
    this.onCompanyChange = this.onCompanyChange.bind(this); 
}

我的渲染:

    public render(): React.ReactElement<IOrderingProps> {
    return (

      <div className={styles.tpOrdering}>
        <div className={styles.container}>

          <Stack tokens={stackTokens}>
            <span className={styles.title}>{this.props.description}</span>
            <Dropdown
              placeholder="Select a company"
              label="Company"
              selectedKey={this.state.companyDropDownSelected}
              id="companyDdl"
              styles={dropdownStyles}
              options={this.props.companyOptions}
              onChange={this.onCompanyChange}
            />
            <PrimaryButton text="Show Comp state" onClick={this.showStateClicked} />                        
            <table id="example" className="display partsTable">
            </table>
          </Stack>

        </div>
      </div>
    );
  }

请注意,我选择的密钥存储在 state 中。我的 onChange 下拉菜单事件:

public onCompanyChange = async (event: React.FormEvent<HTMLdivelement>,item: IDropdownoption): Promise<void> => {    
    const selectedKey: string = item ? (item.key as string) : "";
    this.setState({ companyDropDownSelected: selectedKey });
    this.fetchParts();
  }

这一切正常。但是,如果我更新 WebPart 属性窗格中的任何值,我希望下拉列表保留它的选定值。目前,即使状态保持不变,它也会触发 componentDidUpdate 并清除下拉列表。如何将下拉列表重置为现有的选定键状态?

我的 componentDidUpdate 实现:

public componentDidUpdate(prevProps: IOrderingProps,prevstate: ICurrentWpState,prevContext: any): void {
    // re-execute if limit has changed.
    if (this.props.limit !== prevProps.limit) {
      this.fetchParts();      
    }
  }

即使我在 componentDidUpdate 中什么都不做,它也会清除下拉列表,甚至认为所选键的状态仍然存在。

解决方法

这最终成为一个 async/await 问题,而不是一个状态或控制问题。问题是存储在属性中的 companyOptions 正在从 webpart 传递到组件中。它们是通过对 API 的异步调用创建的。

const element: React.ReactElement<IOrderingProps> = React.createElement(
  Ordering,{
    description: this.properties.description,context: this.context,limit: this.properties.limit,msalInstance: this.msalConfig,companyOptions: await this.getCompanyOptions()
    
  }
);

未正确等待 this.getCompanyOptions() 内的提取和令牌调用。因此,当 companyOptions 仍为 null 时,下拉选择键试图在 componentUpdate 上重置。

<Dropdown
    placeholder="Select a company"
        label="Company"
        selectedKey={this.state.companyDropDownSelected}
        id="companyDdl"
        styles={dropdownStyles}
        options={this.props.companyOptions}
        onChange={this.onCompanyChange}
        />

既然组件更新时有有效选项,这将按预期工作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。