【问题标题】:React ToDoList Project - Unique IDsReact ToDoList 项目 - 唯一 ID
【发布时间】:2021-01-21 00:02:01
【问题描述】:

我正在尝试为列表项引入唯一标识符,而不是使用索引,但是我尝试的每一种方法,我似乎都无法让它在孩子身上发挥作用。这是我正在使用的基础。我确实安装并导入了 import { v4 as uuidv4 } from 'uuid'; 让它更容易一些

你所要做的只是简单地放入'uuidv4()'来生成一个随机ID

家长


import React from 'react';
import './App.css';
import ShoppingCartList from './ShoppingCartList'
import { v4 as uuidv4 } from 'uuid';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      shoppingCart: [],
      newItem: '',
      errorMessage: 'false',
       };
    this.onRemoveItem = this.onRemoveItem.bind(this);

  }
 
handleChange = (e) => {
  this.setState ({ newItem: e.target.value})
  
}  

handleClickAdd = (e) => {   
  if(this.state.newItem === '') {
    this.setState({errorMessage: 'true'});
  } else {
    return (  this.setState({ shoppingCart: this.state.shoppingCart.concat(this.state.newItem) }),
      this.setState({newItem: ''}),
      this.setState({errorMessage: 'false'})
      )}
}



handleSubmit = (e) => {
  e.preventDefault()
  
}

onRemoveItem = (i) => {
  this.setState(state => {
    const shoppingCart = state.shoppingCart.filter((item, j) => i !== j);
    
    return {shoppingCart}

  })}
  

render() {


return (
  <div>
    <form onSubmit ={this.handleSubmit}>
      Shopping Cart Items
      <br></br>
      { this.state.errorMessage === 'true' &&
      <p className='error'> Please enter an item </p> }
      <ul>
        {this.state.shoppingCart.map((item, index,) => {
        return <ShoppingCartList
          item={item}
          index={index}
          onRemoveItem={this.onRemoveItem}
        />
        })}
      </ul>
      <input
      placeholder='Enter your item here'
      value={this.state.newItem}
      onChange={this.handleChange}
      ></input>
      <button type='submit' onClick={this.handleClickAdd}>Add to Shopping list</button>
    </form>

</div>
)
}
}

export default App;


儿童


[code]
import React from 'react';


    function ShoppingCartList ({item,index, onRemoveItem}) {
        return (
            <li key={item}>{item} <button type="button" onClick={() => onRemoveItem(index)}>Delete</button></li>

        )

    }

export default ShoppingCartList;

【问题讨论】:

    标签: javascript reactjs list ecmascript-6 react-props


    【解决方案1】:

    问题

    应该在被映射的元素/组件上定义 React 键,子组件内部的位置错误

    解决方案

    • 将商品添加到购物车时,添加到状态时生成唯一 ID。
    • 在映射购物车时使用项目 id 作为父项中的反应键 物品,并作为识别要从购物车中移除的物品的一种方式。

    更新handleClickAdd 以创建具有 id 和 value 的新项目对象。将现有的购物车数组展开到 new 数组中,并将新的商品对象附加到末尾。

    handleClickAdd = (e) => {
      if (this.state.newItem === "") {
        this.setState({ errorMessage: true });
      } else {
        this.setState((prevState) => ({
          shoppingCart: [
            ...prevState.shoppingCart,
            {
              id: uuidv4(), // <-- new unique id
              value: prevState.newItem // <-- item value
            }
          ],
          newItem: "",
          errorMessage: false
        }));
      }
    };
    

    更新 onRemoveItem 以获取过滤依据。

    onRemoveItem = (id) => {
      this.setState((prevState) => ({
        shoppingCart: prevState.shoppingCart.filter((item) => item.id !== id)
      }));
    };
    

    更新您的渲染以将反应键添加到ShoppingCartList

    {this.state.shoppingCart.map((item) => {
      return (
        <ShoppingCartList
          item={item}
          key={item.id}
          onRemoveItem={this.onRemoveItem}
        />
      );
    })}
    

    更新 ShoppingCartList 以呈现项目值并将项目 ID 传递给删除项目回调。

    const ShoppingCartList = ({ item, onRemoveItem }) => (
        <li>
          {item.value}{" "}
          <button type="button" onClick={() => onRemoveItem(item.id)}>
            Delete
          </button>
        </li>
      );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 2017-12-23
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      相关资源
      最近更新 更多