Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

不要用数组的 index 作 key 值 #10

Closed
MuYunyun opened this issue Oct 17, 2018 · 0 comments
Closed

不要用数组的 index 作 key 值 #10

MuYunyun opened this issue Oct 17, 2018 · 0 comments
Labels
tip This doesn't seem right

Comments

@MuYunyun
Copy link
Owner

MuYunyun commented Oct 17, 2018

在如下 demo 中以数组的 index 作为 key 值,会发生什么呢?

import cpreact, { Component, ReactDOM, PureComponent } from '../src/index'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      items: ['foo', 'bar'],
    }
    this.add = this.add.bind(this)
  }

  add() {
    const items = this.state.items.slice()
    items.unshift('baz')

    this.setState({
      items
    })
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.items.map((r, index) => (
            <li key={index}>
              {r}
              <input />
            </li>
          ))}
        </ul>
        <button onClick={this.add}>add</button>
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)

在 foo 右侧的输入框内输入 1,

image

点击 add 按钮,

image

发现带 1 的输入框依然处在最上面!造成它的原因是因为 diff 前后具有相同的 key 的节点,cpreact/react 只会将新的节点替换掉旧的节点。

@MuYunyun MuYunyun added the tip This doesn't seem right label Oct 17, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
tip This doesn't seem right
Projects
None yet
Development

No branches or pull requests

1 participant