首页 > 解决方案 > 蚂蚁

问题描述

我是第一次在项目中使用 Ant Design。使用 <Option> 和 <Select> 组件我遇到了我遇到过的最奇怪的错误。纯存在 if 代码,即 NOT EXECUTED 改变了 <Option> 的渲染行为。

不同之处在于,第一次(使用代码)它显示一个数字(3),而第二次(没有代码)它显示一个字符串(“Schraube”)。

我不知道我可以分享多少代码,但我录制了一段简短的视频,展示了这个错误。

(打印“GETS CALLED”的代码仅在我更改选择选项后运行,在渲染过程中它不会被执行。)

https://www.youtube.com/watch?v=aY2NPgP5x6A

我想听听你对此的看法。

标签: javascriptreactjsantd

解决方案


在第一种情况下,您有:

if (a) {
    console.log("GETS CALLED");
    return false;
}

return true;

执行此代码时,您的选项未格式化为用户友好的显示。

在第二个你刚刚:

return true;

在这种情况下,它的格式正确。

请注意,这不仅仅是删除console.log语句,而且您不只是启用一些微不足道的if语句。您正在更改函数的返回值。由于这是对您的调用,因此.filter您正在更改传递给哪些值的.map实际格式化选项以用于显示目的。

如果您要尝试:

if (a) {
    console.log("GETS CALLED");
}

return true;

您会看到值被格式化,并且您的console.log语句被命中。

更新我认为你想要完成的是让第二个下拉列表排除在第一个下拉列表中选择的选项。在这种情况下,您需要为每个项目呈现不同的选项数组。还要确保包括为当前下拉列表选择的项目,以便在所选项目上正确显示。这些方面的东西应该会有所帮助:

const orderForm = this.state.order.map((o, i) => {
   const options = this.state.parts
       .filter(p => {
           // look for any *other* order that has this part id selected
           const a = this.state.order.find((o2) => o2 !== o && o2.partId === p.id);
           return !a;
       })
       .map((p) => (<Option ... />));

   return (
      <Select>
         {options}
      </Select>
   );
});

或者,如果您只想渲染<Option>' 一次,您可以执行以下操作:

const allOptions = this.state.parts.map((p) => [p.id, (<Option ... />)]);

const orderForm = this.state.order.map((o, i) => {
   const options = allOptions 
       .filter(([partId]) => {
           // look for any *other* order that has this part id selected
           const a = this.state.order.find((o2) => o2 !== o && o2.partId === partId);
           return !a;
       })
       .map(([_, opt]) => opt);

   return (
      <Select>
         {options}
      </Select>
   );
});

推荐阅读