簡體   English   中英

護送破壞未定義

[英]eslint destructuring coming as undefined

我有一個組件以及相應的動作和減速器。 在操作中,當我進行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' props.product.isFavourited || props.product.'has_favourited_message'因為ES-Lint不允許我這樣使用------ props.product['has_favourited_message'] 我相信,有一種更好的方法,無需更改reducer的鍵或添加注釋eslint-disable-line。

我是新手。 請幫忙。

您可以隨時通過hasOwnProperty('property1')檢查屬性是否存在,以后可以使用

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

我希望我能幫上忙

您的地圖函數語法不正確,需要先包裝()才能分解地圖參數

.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'是無效的語法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM