Answer a question

I'm getting the warning Each child in an array or iterator should have a unique "key" prop. Check the render method of Login

I want to pass an array of elements back, without using keys. I have to believe there's a workaround for this, without adding a pointless wrapper?

Note the return [<div/>, <div/>];

  render () {
    return (
      <div className='login'>
        {this.mobileWeb()}
        {this.pcWeb()}
      </div>
    );
  }

  mobileWeb () {
    if (this.state.isMobileWeb === true) {
      return [
        <div className='sky-container'></div>,
        <div className='sea-container'></div>
      ];
    }
  }

  pcWeb () {
    if (this.state.isMobileWeb !== true) {
      return [
        <div className='sky-container'></div>,
        <div className='sea-container'>
          <LoginForm onChange={this.onChange} ref='loginForm' onEmailChange={this.onEmailChange} onPasswordChange={this.onPasswordChange} />
          <input type='submit' value='Submit' onClick={this.login} />
        </div>
      ];
    }
  }

Answers

There is a valid use case for not wanting to use keys, if you e.g. render strongly differing trees (think blog posts) or have a function that returns always the same array of items.

When you don’t provide an explicit key, React will use the index as key and emit a warning – however you would want to silence the warning, as using the index here is perfectly valid.

This doesn’t seem to be possible however, which has the sad consequence that you either have to make your code more complex for no reason (adding useless keys) or ignore the warnings (which means that valid warnings might be lost among the noise).

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐