美文网首页
Lists and Keys

Lists and Keys

作者: bestCindy | 来源:发表于2020-08-14 09:04 被阅读0次
    const numbers = [1, 2, 3, 4, 5];
    const listItems = numbers.map((number) =>
      <li key={number.toString()}>
        {number}
      </li>
    );
    
    • We need to set a key to each item, keys helpReact identify which items have changed, are added, or are removed
    • When you don't have stable IDs for rendered items, you may use the item index as a key
    const todoItems = todos.map((todo, index) => {
          <li key={ index }>
              { todo.text }
          </li>
    });
    
    • It's is not recommended, and if you not to assign an explicit key to list items then React will default to using indexed as keys
    • Rember the element inside the map() call need keys
    • there is no need to set a key in belos example
    function ListItem(props) {
      const value = props.value;
      return (
        // Wrong! There is no need to specify the key here:
        <li key={value.toString()}>
          {value}
        </li>
      );
    }
    
    • embedding any expression
    function NumberList(props) {
      const number = props.numbers;
      const listItems = numbers.map(number => {
        <listItems key={number.toString()} value ={number} />
      });
      return (
        <ul>
          {listItem}
        </ul>
      );
    }
    

    we could inline the map() in curly braces

    function NumberList(props) {
      const numbers = props.numbers;
    
      return(
        <ul>
          { numbers.map(number => {
              <ListItem key={number.toString()} value={number} />
          }) } 
        </ul>
      );
    }
    

    相关文章

      网友评论

          本文标题:Lists and Keys

          本文链接:https://www.haomeiwen.com/subject/ljcidktx.html