React-动态呈现的语义UI下拉组件的慢状态设置

问题描述 投票:0回答:2

我是React的新手,正在玩语义UI来提高我的技能。但是,在设置下拉列表更改的初始状态和延迟状态更新时遇到了一些麻烦。我正在使用带有集成下拉菜单的语义UI表组件,下面是语义文档here中的示例。本质上,我想根据JSON数组中产品的数量动态呈现表行,每行都有自己的dropdown元素,并预先填充JSON数组中的颜色。在下拉列表更改时,我希望特定索引更新下拉列表的状态。

class DropdownExampleSelection extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentValues: {}
    };
  }

  handleDropdownChange = (index, e, { value }) => {
    this.setState(({ currentValues }) => {
      currentValues[index] = value;
      return currentValues;
    });
  };

  render() {
    const { currentValues } = this.state;
    return (
      <Table celled padded>
        <Table.Header>
          <Table.Row>
            <Table.HeaderCell singleLine>Product</Table.HeaderCell>
          </Table.Row>
        </Table.Header>
        <Table.Body>
          {entries.map((entry, index) => {
            return (
              <Table.Row key={entry._id}>
                <Table.Cell>
                  <Dropdown
                    placeholder="Select Color"
                    selection
                    options={colorOptions}
                    value={currentValues[index]}
                    onChange={this.handleDropdownChange.bind(this, index)}
                  />
                </Table.Cell>
              </Table.Row>
            );
          })}
        </Table.Body>
      </Table>
    );
  }
}

export default DropdownExampleSelection;

See full code on codesandbox.io我有两个问题:1。我不确定为每个下拉菜单设置初始状态的正确方法,该状态应该是预先填充为下拉值的每个产品的“颜色”。请参阅上方codesandbox中的“ entrylist.json”文件以获取数组

{
    "_id": 21,
    "title": "Product 21",
    "color": "red"
  }

2。上面的代码沙箱中的版本更新特定索引处的状态,但这样做时UI会大大滞后。有很多产品,但是我认为这是我代码中的一个问题,因为当我使用语义的默认下拉组件(没有自定义状态设置)codesandbox example here时,它不会滞后,并且条目数量相同。感谢对此的任何指导!

javascript reactjs
2个回答
0
投票

您可以用这个替换您的构造函数(让我知道您的进度)

constructor(props) {
    super(props);
    this.initalstate= entries.map((entry, index) => {
      return entry.color
    })
    this.state = {
      currentValues: {...this.initalstate}
    };

  }

0
投票

如果您仍在寻找改善此性能的方法。我有一些建议。

@@ depish已经说过,即使只更改了1个下拉菜单,您的下拉菜单组件也太多,并且每个组件都被重新渲染。从这一点开始,我们提出一个问题,如何仅渲染其值已更改的Dropdown?

为了做到这一点,您需要在下面分开代码

        return (
          <Table.Row key={entry._id}>
            <Table.Cell>
              <Dropdown
                placeholder="Select Color"
                selection
                options={colorOptions}
                value={currentValues[index]}
                onChange={this.handleDropdownChange.bind(this, index)}
              />
            </Table.Cell>
          </Table.Row>
        );

传递到外部React.PureComponent,并传递它需要的所有参数(值,handleDropdownChange)。由于仅当父项或状态更改产生其他道具时才重新渲染PureComponent。

它应该通过渲染所有150个下拉菜单来解决您的问题

祝你好运

© www.soinside.com 2019 - 2024. All rights reserved.