首页 > 解决方案 > 反应“no-unused-vars”和属性未定义错误

问题描述

因为我刚开始学习 JavaScript,所以我似乎没有解决未使用变量和属性未定义的问题。

我正在使用带有箭头函数和上下文 API 的 ES6 而不是道具

有 4 个文件夹抱怨 no-unused-vars。它们似乎是破坏代码的唯一问题。我试图通过使用“// eslint-disable-next-line”来禁用它,但没有成功。

我是 JavaScript 新手,所以感谢所有帮助。

错误是:

export default function App(){
 
  const [{user, token}, dispatch] = useDataLayerValue();

  useEffect(() => {
    const hash = getTokenFromUrl();
    window.location.hash = "";
    const _token = hash.access_token;

    if (_token) {
      dispatch({
        type: "SET_TOKEN",
        token: token,
      });

      spotify.setAccessToken(_token);
      spotify.getMe().then((user) => {
        dispatch({
          type: "SET_USER",
          user: user
        });
      });

      spotify.getUserPlaylists().then((playlists) => {
        dispatch({
          type:"SET_PLAYLISTS",
          playlists: playlists,
        });
      });

      spotify.getPlaylist('37i9dQZEVXcGE3bYuPUwd6?si=FFY51lL3QUK21r_TYY14RQ').then(response => {
        dispatch({
          type: "SET_DISCOVER_WEEKLY",
          discover_weekly: response,
        });
      });
    };
  }, []);

  return (
    <div className="app">
      {token ?  <Player /> : <Login/> }
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

***this is the file with the useDataLayerValue const***

import React, { createContext, useContext, useReducer} from "react";

export const DataLayerContext = createContext();

export const DataLayer = ({ initialState, reducer, children}) => (
  <DataLayerContext.Provider  value={useReducer(reducer, initialState)}>
    {children}
  </DataLayerContext.Provider>
);

export const useDataLayerValue = () => useContext(DataLayerContext);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

标签: javascriptreactjs

解决方案


无法读取未定义的属性“用户”:发生这种情况,因为

const DataLayerContext = createContext();
const useDataLayerValue = () => useContext(DataLayerContext);

您正在创建一个提供空对象的上下文。并且空对象没有称为 的成员user。他们根本没有任何成员。user我猜你是在之后设置了这个成员,所以你必须在你想使用它的地方检查 unset 。或者您也可以在开头提供一个默认对象,如下所示:

const defaultDataLayerContext = {user: 'some default user'};
const DataLayerContext = createContext(defaultDataLayerContext);
const useDataLayerValue = () => useContext(DataLayerContext);

'dispatch' 被分配了一个值但从未使用过:这是 eslint 的警告,它说

const [{user, token}, dispatch] = useDataLayerValue();

定义dispatch,但您不在代码中使用它。所以要么删除dispatch或配置你的 eslint 以不显示此警告。


推荐阅读