当前位置: 代码迷 >> JavaScript >> React:是否可以在不更新其兄弟姐妹的情况下将项目添加到列表中?
  详细解决方案

React:是否可以在不更新其兄弟姐妹的情况下将项目添加到列表中?

热度:101   发布时间:2023-06-03 18:14:39.0

比方说我有:

class Item extends React.Component {
  render() {
    console.log('Let's assume this does something slow...');
    return <li>{this.props.text}</li>;
  }
}


class List extends React.Component {
  constructor() {
    super();
    this.state = {
      items: [],
    };
  }
  addItem = text => {
    this.setState({
      // Mutates the array reference... is there a way around it?
      items: this.state.items.concat({ id: Math.random(), text }),
    });
  };
  render() {
    return (
      <div>
        <button onClick={() => this.addItem(Math.random())}>Add Item</button>
        <ul>
          // This will run on every render, re-rendering the whole list...
          {this.state.items.map(item => (
            <Item key={item.id} text={item.text} />
          ))}
        </ul>
      </div>
    );
  }
}

是否有可能使现有列表保持不变,我只是在顶部/底部添加一个新项目而不调用其兄弟姐妹的render()

React Component将始终被重新渲染,但实现了一个带有浅的prop和状态比较的shouldComponentUpdate ,因此除非更改了props,否则它不会重新渲染。

 class Item extends React.PureComponent { render() { console.log("Let's assume this does something slow..."); return <li>{this.props.text}</li>; } } class List extends React.Component { state = { items: [] }; addItem = text => { this.setState(prevState => { return { items: [...prevState.items, { id: Math.random(), text }] }; }); }; render() { return ( <div> <button onClick={() => this.addItem(Math.random())}>Add Item</button> <ul> {this.state.items.map(item => ( <Item key={item.id} text={item.text} /> ))} </ul> </div> ); } } ReactDOM.render(<List />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div> 

  相关解决方案