How unique should a React component Key be?

后端 未结 2 500
野趣味
野趣味 2020-12-18 19:06

This is a quick one: what is the scope in which the children keys have to be unique? Is this just the parent component or the whole app?

If the latter is true, does

2条回答
  •  伪装坚强ぢ
    2020-12-18 19:51

    Yes, looks like it...if you re-parent it, it'll give a different reactid (eg. http://webcloud.se/react-sortable/nested.html )

    and will unmount/re-mount again. ...

    http://jsfiddle.net/46x0j6uq/1/

    ,componentWillUnmount: function() {
     //console.log("unmounted:", this.props);
     clearInterval(this.state.intervalId);
     clearTimeout(this.state.timeoutId);
    }
    ,componentDidMount: function(){
      // console.log("mounted:", this.props);
      this.state.intervalId = setInterval(this.incrementCount, 1000);
     this.state.timeoutId = setTimeout(this.setColorToBlack, 300);
    }
    

    So, better not to store state in the view component itself, since it might reset itself. The above fiddle is just a demo to prove a point.

    Other related links: Using keys to identify nested components in React.js

    I did wish React had something to consider scoped/nested key states beyond the same level, but i guess the performance of unmounting/re-mounting again should hopefully not be too detrimental.

提交回复
热议问题