简体   繁体   English

React / Redux组件重新渲染

[英]React / Redux components rerendering

Hi I have been using React / Redux for may App. 嗨,我一直在为May App使用React / Redux。 I have to render multiple input fields dynamically. 我必须动态呈现多个输入字段。 The problem which I am facing right now is... 我现在面临的问题是...

So suppose, the form already have 2 input fields, and I want 5 input fields total, I will simply render these with the help of a loop with 5 repetitions. 因此,假设表单已经有2个输入字段,而我总共希望有5个输入字段,那么我将借助5个重复的循环来简单地渲染这些输入字段。 the problem is react renders 3 new fields and keeps 2 old at top. 问题是反应会渲染3个新字段,并保留2个旧字段。 But I need fresh 5 fields. 但是我需要5个新领域。 Is there a way to force react to remove old fields first and then render 5 new fields. 有没有一种方法可以强制反应先删除旧字段,然后渲染5个新字段。

The problem is in the key attribute. 问题出在关键属性上。 If you give the components new keys each render, then the fields will be recreated 如果为每个渲染组件赋予新的键,则将重新创建字段

A small example is below. 下面是一个小例子。 I used Math.and() to generate unique keys. 我使用Math.and()生成唯一键。 Of course, better to use shortid or similar 当然,最好使用shortid或类似的符号

https://www.npmjs.com/browse/keyword/shortid https://www.npmjs.com/browse/keyword/shortid

class InputRenderer extends Component {

  constructor() {
    super()
    this.state = {
      inputsCount: 3
    }
  }

  handleInputsCountChange = (newCount) => {
    this.setState({
      inputsCount: newCount
    })
  }

  renderInputs = () => {
    const inputs = []
    for (let i = 0; i < this.state.inputsCount; i++) {
      inputs.push(<input key={i + Math.random()} />)
    }
    return inputs
  }

  render = () =>
    <div>
      <button onClick={() => this.handleInputsCountChange(3)}>3</button>
      <button onClick={() => this.handleInputsCountChange(5)}>5</button>
      {this.renderInputs()}
    </div>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM