首页 > 解决方案 > React Native - 为 useSelector 设置一个简单的变量

问题描述

我需要设置一个变量以与 useSelector (redux) 一起使用,看起来很简单,但我不知道该怎么做。

  const CATEGORY = cat;
  console.log(CATEGORY); // correctly get the strings 'food' or 'design'

  const getItems = useSelector(state => state.appDb.CATEGORY);
  console.log(getItems); // I get undefined

基本上我想使用变量来设置这个:

state.appDb.food或者state.appDb.design

什么是正确的语法?

标签: react-nativereact-redux

解决方案


所有你需要用来brackets notation访问动态对象键,如

  const CATEGORY = cat;
  console.log(CATEGORY); // correctly get the strings 'food' or 'design'

  const getItems = useSelector(state => state.appDb[CATEGORY]);
  console.log(getItems);

推荐阅读