【问题标题】:how to access to a function inside a class component from another function? [duplicate]如何从另一个函数访问类组件内的函数? [复制]
【发布时间】:2021-05-07 08:24:03
【问题描述】:

我是 React 的新手,我正在尝试编写一个使用 API 的应用程序。代码更广泛,所以我把问题部分删掉并放在这里,我不知道这是否可能做到,所以如果有人知道怎么做,那将是一个很大的帮助。

-解释
当我调用 deleteProduct() 通过 props 传递给外部函数 listTemplate.js 时,内部 getProducts() 给了我这个错误:

未处理的拒绝(TypeError):this.getproducts 不是函数

export default class test extends Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [],
    };
  }
  async componentDidMount() {
    this.getproductos();
  }

  async getproducts() {
    const res = await axios.get("http://localhost:5000/api/productos");
    this.setState({ products: res.data });
    //Set in products info like {products:[name: 'shoes', model:'XXL', price:'90' ]}.
  }

  async deleteProduct(id) {
    await axios.delete("http://localhost:5000/api/productos/" + id); //Delete selected product.
    this.getproductos(); //get actualized products array.
  }

  render() {
    const { products } = this.state;
    return (
      <div className="col-md-6">
        <ListTemplate products={products} delBtn={this.deleteProduct} /> //here i pass through listTemplate deleteProduct() function.
      </div>
    );
  }
}



/******************************************************************************/

在另一个 .js 文件中我有这个:

export default function ListTemplate(props) {
  const { products } = props.product;
  return (
    <div className="container">
      <div className="header">
        <h2>Product List:</h2>
      </div>
      {products.map((product) => (
        <div class="body" key={product._id}>
          <span>{product.name}</span>
          <span>{product.model}</span>
          <span>${product.price}</span>
          <button
            type="button"
            class="btn btn-danger btn-sm"
            onClick={(e) => {
              props.delBtn(product._id);
            }}
          >
            Delete Item
          </button>
        </div>
      ))}
    </div>
  );
}

我的问题是当deleteProduct() 完成并尝试getProduct() 时。爆炸。

【问题讨论】:

  • 尝试将delBtn={this.deleteProduct}更改为delBtn={() =&gt; this.deleteProduct()}

标签: reactjs function components this react-component


【解决方案1】:

尝试创建一个箭头方法,如

deleteProduct = async (id) => {
    ...
}

【讨论】:

  • 谢谢各位,我的问题使用箭头功能消失了。谢了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 2020-03-05
  • 1970-01-01
相关资源
最近更新 更多