What is the significance of keys in ReactJS?

后端 未结 2 1732
遇见更好的自我
遇见更好的自我 2020-12-28 16:39

I want to understand what happens if I don\'t use keys in dynamically added components. I removed keys and it renders without any issue and just gave warning messages regard

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 17:09

    Another useful usage of React keys other than creating dynamic elements is reseting elements when their keys change, for example in a project I had an element of type file and I wanted the element to be initialized to its initial value (no file chosen) each time the component renders, so I did the following:

    Parent constructor:

    this.state = {
        fileInputKey: Date.now()
        // other properties
    };
    

    The state object also had other properties, I just added this one for the sake of this example

    Each time I wanted the input element in the child component be reset I did:

    this.setState({fileInputKey: Date.now()});
    

    Parent render:

    
    

    Child render:

    
    

    Also see this example from React blog: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

提交回复
热议问题