【问题标题】:Reactjs: re-renders iframes when state changedReactjs:当状态改变时重新渲染 iframe
【发布时间】:2014-09-30 16:09:58
【问题描述】:

我在每个列表项中创建了一个包含列表和 iframe 的示例。

http://jsfiddle.net/codez/kpth3szj/

/** @jsx React.DOM */
var TodoList = React.createClass({
  createItem: function(item) {
      return (
          <li>{item.text} <a href="#" onClick={this.props.handleDelete.bind(this, item)}>x</a><br />
        <iframe width="560" height="315" src={item.yid} frameborder="0" allowfullscreen></iframe>
           </li>        
      );
  },

  render: function() {
    return <ul>{this.props.items.map(this.createItem)}</ul>;
  }
});

var TodoApp = React.createClass({
  getInitialState: function() {
    return {items: [
    {text:'hello',name:'name1',yid:'//www.youtube.com/embed/y3iZACDBapU?autoplay=1'},
    {text:'hello2',name:'name2',yid:'//www.youtube.com/embed/dA3nu8ht0jU?autoplay=1'}
    ], text: ''};
  },
  handleDelete: function(itemToDelete, e) {
    console.info(itemToDelete);
    var newItems = _.reject(this.state.items, function(item) {
        return item.name == itemToDelete.name
    });
    this.setState({items: newItems});
  },
  handleChange: function(e) {
    this.setState({text: e.target.value});
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var nextItems = this.state.items.concat([this.state.text]);
    var nextText = '';
    this.setState({items: nextItems, text: nextText});
  },
  render: function() {
    return (
      <div>
        <h3>TODO</h3>
        <TodoList items={this.state.items} handleDelete={this.handleDelete} />
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.handleChange} value={this.state.text} />
          <button>{'Add #' + (this.state.items.length + 1)}</button>
        </form>
      </div>
    );
  }
});
React.renderComponent(<TodoApp />, document.body);

如果我从状态中删除记录,其他记录的 iframe 将重新呈现。 如果您尝试删除示例中的第一个记录,则第二个视频将从头开始。

如何告诉 Reactjs 不要重新渲染状态不变的记录?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    尝试在 Todolist createitem 函数中添加一个 key 属性

    var TodoList = React.createClass({
      createItem: function(item) {
          return (
              <li key={item.yid}>
                  {item.text} 
                  <a href="#" onClick={this.props.handleDelete.bind(this, item)}>x</a><br />
                  <iframe src={item.yid} width="560" height="315" frameborder="0" allowfullscreen></iframe>
               </li>        
          );
      },
    
      render: function() {
        return <ul>{this.props.items.map(this.createItem)}</ul>;
      }
    });
    

    http://facebook.github.io/react/docs/multiple-components.html#dynamic-children

    【讨论】:

      猜你喜欢
      • 2019-08-08
      • 2022-11-06
      • 2020-04-22
      • 2020-09-30
      • 1970-01-01
      • 2020-01-20
      • 2020-09-10
      • 2019-05-22
      • 1970-01-01
      相关资源
      最近更新 更多