When giving unique keys to components, is it okay to use Math.random() for generating those keys?

后端 未结 7 1635
谎友^
谎友^ 2020-12-04 23:44

Problem is the following:

I have data in form of a list of a few thousand elements. Some of them are duplicates, and there might be the chance of having duplicate ke

相关标签:
7条回答
  • 2020-12-05 00:21

    Is this a good practice? Can I use this without having to worry about anything?

    No and no.

    Keys should be stable, predictable, and unique. Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.

    Let me illustrate this with a simple example.

    class Input extends React.Component {
      handleChange = (e) =>  this.props.onChange({
        value: e.target.value,
        index: this.props.index
      });
      render() {
        return (
          <input value={this.props.value} onChange={this.handleChange}/>  
        )
      }
    };
    
    class TextInputs extends React.Component {
      state = {
        textArray: ['hi,','My','Name','is']
      };
      handleChange = ({value, index}) => {
        const {textArray} = this.state;
        textArray[index] = value;
        this.setState({textArray})
      };
      render(){
      return this.state.textArray.map((txt, i) => <Input onChange={this.handleChange} index={i} value={txt} key={Math.random()}/>)
      // using array's index is not as worse but this will also cause bugs.  
      // return this.state.textArray.map((txt, i) => <Input onChange={this.handleChange} index={i} value={txt} key={i}/>)                 
      };
    };
    

    Why can't i type in more than one character in the inputs you ask?

    It is because I am mapping multiple text inputs with Math.random() as key prop. Every time I type in a character the onChange prop fires and the parent component's state changes which causes a re-render. Which means Math.random is called again for each input and new key props are generated.So react renders new children Input components.In other words every time you type a character react creates a new input element because the key prop changed.

    Read more about this here

    0 讨论(0)
提交回复
热议问题