eslint destructuring is undefined

时间:2018-04-19 11:58:34

标签: javascript reactjs react-native eslint destructuring

我有一个组件及相应的操作和缩减器。 在操作中,当我进行API调用时,我会像这样进行调用

    export const getData = () => {
     return axios.post(url, data, headers){
               .then((response)=>{
                  const messages = response.data.map({has_favourited_message: isFavourited}) //I am doing this since ESLINT throws errors
=>({isFavourited})
    })
    return messages;
     }
    }

在组件中,我正在使用它

class ProductView extends React.Component {
  constructor(props) {
    super(props);
    this.state = { page: 0, imageUrls: [], isFavourited: props.product.isFavourited || props.product['has_favourited_message']
  }
render(){
  return null;
}
}

在减速机中,我有

case GET_DATA:
      return {
        ...state,
        data: state.data.map((item) => {
          if (item.id !== action.payload.id) return item;
          return { ...state, ...item, has_favourited_message: action.payload.isFavourited }; //Here I don't want to add any extra key so I am using the original key only as I am dispatch the above action to multiple reducers so it would become inconsistent if I change the key
        }),
      };

我正在使用props.product.isFavourited || props.product.'has_favourited_message'因为ES-Lint不允许我像这样使用------ props.product['has_favourited_message']。 我相信有一种更好的方法可以在不改变reducer中的键或添加注释eslint-disable-line的情况下执行此操作。

我是desructuring的新手。请帮忙。

2 个答案:

答案 0 :(得分:0)

您可以随时通过 hasOwnProperty(' property1') 检查属性是否存在 稍后你可以使用

props.product.hasOwnProperty('has_favourited_message') ?props.product.has_favourited_message : 'There is no favourited message' 

我希望我会帮忙

答案 1 :(得分:0)

您映射函数语法不正确,在解构映射参数之前需要包装()

.then((response)=>{                     
     const messages = response.data.map(({has_favourited_message: isFavourited}) => ({isFavourited})
     return messages;
 })

而不是props.product.'has_favourited_message',您应该写props.product.has_favourited_message,因为props.product.'has_favourited_message'语法无效