javascript - 反应“no-unused-vars”和属性未定义错误
问题描述
因为我刚开始学习 JavaScript,所以我似乎没有解决未使用变量和属性未定义的问题。
我正在使用带有箭头函数和上下文 API 的 ES6 而不是道具
有 4 个文件夹抱怨 no-unused-vars。它们似乎是破坏代码的唯一问题。我试图通过使用“// eslint-disable-next-line”来禁用它,但没有成功。
我是 JavaScript 新手,所以感谢所有帮助。
错误是:
- 无法读取未定义的属性“用户”
- 'dispatch' 被分配了一个值,但从未使用过 no-unused-vars
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>
解决方案
无法读取未定义的属性“用户”:发生这种情况,因为
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 以不显示此警告。
推荐阅读
- python - 将 utf-8 字符转换为 Scandic 字母
- python - 处理包时导入和重新加载实际如何工作
- typo3 - 如何在 MASK 扩展中使用模板部分
- python-3.x - 下载文件时 Tkinter UI 被阻止
- android - 收到“错误:发生意外错误。” 在部署firebase功能时
- spring-webflux - R2DBC - IllegalArgumentException:无法编码 java.util.Date 类型的参数
- map-api - 获取多边形的编辑坐标
- .net - 如何从 .NET Core MVC 调用具有多个参数的 API
- java - JBoss 上的 Java 缓存
- oracle - 如何将数字与 varchar2 列分开?