无法理解React语法

时间:2016-12-23 22:13:11

标签: reactjs

我想了解React& Redux更好。最近我一直在使用这里的例子:https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js
我很难掌握这些方面: ... action.products.reduce((obj,product)=> {  obj [product.id] =产品  返回obj  },{})

和[productId]:产品(州[productId],行动)

有人可以解释一下发生了什么吗?

const byId = (state = {}, action) => {
  switch (action.type) {
    case RECEIVE_PRODUCTS:
      return {
        ...state,
        ...action.products.reduce((obj, product) => {
          obj[product.id] = product
          return obj
        }, {})
      }
    default:
      const { productId } = action
      if (productId) {
        return {
          ...state,
          [productId]: products(state[productId], action)
        }
      }
      return state
  }

1 个答案:

答案 0 :(得分:1)

你的问题不明确,但我会尽力回答我的能力。 ...(三个点)被称为spread operator,它是"合并"的一种方式。一个对象(或数组)到另一个对象(或数组)。这是一个例子:

const objA = {
    field_1: "my value",
    field_2: "my other value"
};
const newObject = {
    ...objA,
    field_3: "my third value"
};
console.log(newObject); // { 
                        //   field_1: "my value", 
                        //   field_2: "my other value", 
                        //   field_3: "my third value" 
                        // }

它基本上等同于以下内容:

const objA = {
    field_1: "my value",
    field_2: "my other value"
};
const newObject = Object.assign({}, objA, { field_3: "my third value" });

除此之外还有更多内容,所以请参阅文档。

[productId]: products(state[productId], action)是一种将变量用作对象键的方法。这大致相当于:

let objA = {
    field_1: "my value",
};
const myKey = "field_2";
objA[myKey] = "my other value";

从技术上讲,它不是React语法,而是评估ES6-7语法。

相关问题