【问题标题】:eslint destructuring coming as undefinedeslint 解构未定义
【发布时间】:2018-09-29 22:14:24
【问题描述】:

我有一个组件和相应的动作和减速器。 在操作中,当我进行 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;
}
}

在reducer中,我有

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。

我是解构的新手。请帮忙。

【问题讨论】:

  • 它会引发 ESlint 问题
  • 它对props.product['has_favourited_message'] 显示什么警告?这让我很吃惊。
  • 它给出的错误是 props.product['has_favourited_message'] 应该更好地用点表示法编写。 @安迪
  • 应该是props.product.has_favourited_message 而不是props.product.'has_favourited_message'

标签: javascript reactjs react-native eslint destructuring


【解决方案1】:

您始终可以通过 hasOwnProperty('property1') 检查属性是否存在 以后可以使用

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

希望能帮到你

【讨论】:

    【解决方案2】:

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

    .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'是一个无效的语法

    【讨论】:

    • 对不起,我在我的问题中错过了这一点。写的和你建议的答案一样,但我的问题是别的
    猜你喜欢
    • 2018-02-12
    • 2018-11-26
    • 2017-01-23
    • 2021-02-01
    • 2018-07-13
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多