javascript - React - 组件中的折射状态

标签 javascript reactjs

我有一个将 Logo 填充到网格系统中的组件。它获得 2 个属性,分别是 grid - 接受 Logo 和 limit - 显示的 Logo 数量。

  type Props = {
    grid: [],
    limit: number,
  };

  type State = {
    grid: any,
    queue: any,
  };

  class LogoGrid extends Component<Props, State> {

    state = {
      grid: Object.keys(this.props.grid).map(name => ({name, key: name})).slice(0, this.props.limit),
      queue: Object.keys(this.props.grid).map(name => ({name, key: name})).slice(this.props.limit, Object.keys(this.props.grid).length),
    };

    componentDidMount() {
      this.interval = setInterval(this.updateQueue, SWAP_INTERVAL);
    }

    componentWillUnmount() {
      clearInterval(this.interval);
    }

    getRandomInt = (min: number, max: number) => Math.floor((Math.random() * (max - min)) + min);

    updateQueue = (): void => {
      const { limit } = this.props;
      const grid = [...this.state.grid];
      const queue = [...this.state.queue];
      const replaceIndex = this.getRandomInt(0, limit);
      const removedItem = grid.splice(replaceIndex, 1, queue.shift());
      queue.push(removedItem[0]);

      this.setState({ grid, queue });
    }


    render() {
      const { grid } = this.state;

      return (
        <div className={css.container}>
          {grid.map((item, i) => (          
            <CSSTransitionGroup
              transitionName={css}
              transitionEnterTimeout={SWAP_INTERVAL - 100}
              transitionLeaveTimeout={SWAP_INTERVAL - 100}
            >
              <Logo key={i} name={item.name} color="white" className={css.logo}/>
            </CSSTransitionGroup>
          ))}
        </div>  
      );
    }
  }

  export default LogoGrid;

在父组件中,它将按如下方式使用:

  <LogoGrid grid={rawLogos} limit={12} />

rawLogos 在这种情况下只是 Logo 的 js 文件,如下所示:

  const url = (filename) => `${process.env.S3_LOGOS_BASE_URL}/logo-${filename}`;

  export default {
    '26grains': url('26grains.svg'),
    ...
    ...
  };

我的问题是如何进一步简化/重构 LogoGrid 组件,特别是 state 的编写方式。

更新:

我尝试这样做,但收到错误:Uncaught TypeError:无法读取未定义的属性“map”

  state = {
    grid: this.gridItems,
    queue: this.queueItems,
  };

  gridItems = () => {
    const logoGrid = Object.keys(this.props.grid).map(name => ({name, key: name})).slice(0, this.props.limit);
    this.setState({grid: logoGrid})
  }

  queueItems = () => {
    const queueGrid = Object.keys(this.props.grid).map(name => ({name, key: name})).slice(this.props.limit, Object.keys(this.props.grid).length);
    this.setState({queue: queueGrid})
  }

最佳答案

初始化时无法设置状态。

您可以在此处查看示例:https://codesandbox.io/s/reverent-hill-vvet2

或者在这里:

const items = ["hi", "test", "3"];

class MyClass extends React.Component {
  state = {
    items: []
  };

  componentDidMount() {
    this.setItems();
  }

  setItems() {
    console.log(this.props.items);
    const items = this.props.items.map(i => <p>{i}</p>);
    console.log(items);
    this.setState({
      items
    });
  }

  render() {
    return <div>{this.state.items}</div>;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyClass items={items} />, rootElement);

解决方案:

在使用 componentDidMount 初始化状态后设置您的状态,如示例中所示。

关于javascript - React - 组件中的折射状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59087722/

相关文章:

javascript - 将 <li> 拖动到两个 <ul> JS 之间(不使用 jQuery)

javascript - React JS - 单击更改颜色并将默认颜色放在所有其他颜色上

javascript - 如何克服异步useState钩子(Hook)?

javascript - 如何从 JSON 数组中获取集合

Javascript 使用变量作为键来获取嵌套对象值

javascript - 如何在通过 iframe 查看网页时静音

javascript - 在reactjs中通过不同的id从api获取数据

javascript - React Carousel renderArrow 常量未定义

javascript - 在组件渲染中调用高阶组件

javascript - 使用滚动条淡入一堆图像(div)