更喜欢解构es-lint错误

时间:2018-01-09 14:52:31

标签: javascript reactjs eslint destructuring

我有这个功能:

public class ProductAdapter  extends  RecyclerView.Adapter<ProductAdapter.ViewHolder>{

public static ClickListener clickListener;

public List<Info> documents;
private Activity context;
private FirebaseFirestore firestoreDB;

public ProductAdapter(List<Info> list, Activitx ctx,   FirebaseFirestore firestore) {
documents = list;
context = ctx;
firestoreDB = firestore;
}

@Override
 public int getItemCount() {
 return documents.size();
 }

@Override
public ProductAdapter.ViewHolder
 onCreateViewHolder(ViewGroup parent, int viewType) {

 View view = LayoutInflater.from(parent.getContext())
        .inflate(R.layout.list_layout, parent, false);

 ProductAdapter.ViewHolder viewHolder =
        new ProductAdapter.ViewHolder(view);
 return viewHolder;
}

@Override
 public void onBindViewHolder(ProductAdapter.ViewHolder holder, int position) {
 final int itemPos = position;
 final Info model = documents.get(position);
 holder.item_name.setText(model.getProduct());
  holder.price.setText("Rs " + model.getCost() + "/" +  model.getPer());

  holder.itemView.setOnClicListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent openNewActivity = new Intent(context, YourNewActivity.class);
              openNewActivity.putExtra("id", model.getId());
              openNewActivity.putExtra("product", model.getProduct());
              context.startActivity(openNewActivity);
            }
        }); 


 }

 public class ViewHolder extends RecyclerView.ViewHolder implements      View.OnClickListener {

  public TextView item_name;
  public TextView price;


     public ViewHolder(View view) {
     super(view);
     itemView.setOnClickListener(this);
     item_name = view.findViewById(R.id.List_maintext);
     price = view.findViewById(R.id.List_subtext);

  }

 @Override
  public void onClick(View v) {
    clickListener.onItemClick(getAdapterPosition(), v);

  }
  } 
  public void setOnItemClickListener(ClickListener clickListener) {
  ProductAdapter.clickListener = clickListener;


}

public interface ClickListener {
void onItemClick(int position, View v);

}

}

如何通过ES6 +解构来解决这个问题?

我知道我需要(第4行):

const calculateTotal = (items) => { return items.reduce((totalPrice, basketItem) => { const price = basketItem.product.price; const quantity = basketItem.quantity; const total = price * quantity; return totalPrice + total; }, 0); };

但是我无法让第3行工作

2 个答案:

答案 0 :(得分:6)

const quantity=basketItem.quantity;

在这种解构方法之下:

const {quantity}=basketItem;

答案 1 :(得分:6)

根据您尝试的操作,您可以执行此操作,从price获取product,从quantity获取basketItem,而无需在两个单独的行上声明变量。

const calculateTotal = (items) => {
  return items.reduce((totalPrice, basketItem) => {
    const { product: { price }, quantity } = basketItem;

    const total = price * quantity;
    return totalPrice + total;
  }, 0);
};