使用useContext钩子时如何避免"setState never used"



我知道如果你有这样的东西…

const [state, setState] = useState('some state');

如果你得到setState从未使用过的警告,你就不应该使用estate,而应该使用一个正常的变量。

我的问题是,如果这是useContext而不是useState,如下所示?我为其他组件设置了这个结构,但有些组件不需要为此上下文设置setState。如何处理此警告?eslint是我唯一的选择吗?

const [state, setState] = useContext(myContext);

我有另一个组件,使用setState,但不使用状态。我该如何处理?

如果你不打算使用它,就不要解构它:

const [state] = useContext(myContext);

您的useContext(和useState)返回一个数组。只要解构在这些位置的

const useState = () => ["hi", "mom"];
const [position_0, position_1] = useState();

console.log(postition_0) // "hi"
console.log(postition_1) // "mom"

如果你想跳过一个变量,你可以使用一个一次性变量,如:

const [, position_1] = useState();

更多细节见本文。

如果您控制上下文,但是,我个人首选的选项是返回object而不是array,如下所示:

const context = () => {
...your context here...
return {
state,
setState,
...even more...
}
)

这样,你可以简单地只解构你需要的东西:

const { state } = useContext(context); // just state
const { setState } = useContext(context); // just setState
const { state, setState } = useContext(context); // both

最新更新