如何使 useEffect 的值全局可用(或在 useEffect 之外)

时间:2021-04-24 06:50:49

标签: javascript arrays reactjs

我在 useEffect 之外初始化了一个数组,然后在 useEffect 中对数组执行了某些操作。当我在 useEffect 内打印数组时,我得到了正确的值,但是如果我在 useEffect 外打印相同的数组,我会得到一个空数组作为结果。

只要 useState 中的“values”数组发生变化,useEffect 就会运行。

import Menu from './data';
const App = () => {
const [values, setvalues] = useState([]);
  const [ids, setids] = useState([]);
  let arrIds = [];
  let arrValue = [];
  var n = values.length;
  useEffect(() => {
    console.log("useEffect", values); //output: ["Frontend"]
    arrValue = [];
    Menu.filter(x => {
      if(values.includes(x.role)) {
        arrValue.push(x.id);
      }
      if(values.includes(x.level)) {
        arrValue.push(x.id);
      }
      if(x.languages.length > 0) {
        for(var i=0;i<n;i++) {
          if(x.languages.includes(values[i])) {
            arrValue.push(x.id);
          }
        }
      }
      if(x.tools.length > 0) {
        for(var i=0;i<n;i++) {
          if(x.tools.includes(values[i])) {
            arrValue.push(x.id);
          }
        }
      }
    });
    console.log("new array of id", arrValue); // output: [1, 3, 4, 7, 8, 10]
    arrValue = [...new Set(arrValue)];
    console.log("new array of id without repetition", arrValue); // output: [1, 3, 4, 7, 8, 10]
    if(arrValue) {
      arrIds.push(...arrValue);
      for(var a = 0;a<arrValue.length;a++) {
        var at = arrValue[a]
        console.log('arr val',at)
        setids(ids => [...ids, at]); 
      }
      console.log("setids ", ids);// output:[](not able to store the value of "at" in "ids" useState Array
      console.log("arrIds", arrIds);// output: [1, 3, 4, 7, 8, 10]
    }
  }, [values]);
console.log("arrIds", arrIds);// output:[] (empty array recieved outside the useEffect)
}

data.js 文件包含对象数组:

export default [
  {
    "id": 1,
    "company": "Photosnap",
    "logo": Photosnap,
    "new1": true,
    "featured": true,
    "position": "Senior Frontend Developer",
    "role": "Frontend",
    "level": "Senior",
    "postedAt": "1d ago",
    "contract": "Full Time",
    "location": "USA Only",
    "languages": ["HTML", "CSS", "JavaScript"],
    "tools": []
  },
  {
    "id": 2,
    "company": "Manage",
    "logo": manage,
    "new1": true,
    "featured": true,
    "position": "Fullstack Developer",
    "role": "Fullstack",
    "level": "Midweight",
    "postedAt": "1d ago",
    "contract": "Part Time",
    "location": "Remote",
    "languages": ["Python"],
    "tools": ["React"]
  },
  {
    "id": 3,
    "company": "Account",
    "logo": account,
    "new1": true,
    "featured": false,
    "position": "Junior Frontend Developer",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "2d ago",
    "contract": "Part Time",
    "location": "USA Only",
    "languages": ["JavaScript"],
    "tools": ["React", "Sass"]
  },
  {
    "id": 4,
    "company": "MyHome",
    "logo": myhome,
    "new1": false,
    "featured": false,
    "position": "Junior Frontend Developer",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "5d ago",
    "contract": "Contract",
    "location": "USA Only",
    "languages": ["CSS", "JavaScript"],
    "tools": []
  },
  {
    "id": 5,
    "company": "Loop Studios",
    "logo": loopstudios,
    "new1": false,
    "featured": false,
    "position": "Software Engineer",
    "role": "FullStack",
    "level": "Midweight",
    "postedAt": "1w ago",
    "contract": "Full Time",
    "location": "Worldwide",
    "languages": ["JavaScript"],
    "tools": ["Ruby", "Sass"]
  },
  {
    "id": 6,
    "company": "FaceIt",
    "logo": faceit,
    "new1": false,
    "featured": false,
    "position": "Junior Backend Developer",
    "role": "Backend",
    "level": "Junior",
    "postedAt": "2w ago",
    "contract": "Full Time",
    "location": "UK Only",
    "languages": ["Ruby"],
    "tools": ["RoR"]
  },
  {
    "id": 7,
    "company": "Shortly",
    "logo": shortly,
    "new1": false,
    "featured": false,
    "position": "Junior Developer",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "2w ago",
    "contract": "Full Time",
    "location": "Worldwide",
    "languages": ["HTML", "JavaScript"],
    "tools": ["Sass"]
  },
  {
    "id": 8,
    "company": "Insure",
    "logo": insure,
    "new1": false,
    "featured": false,
    "position": "Junior Frontend Developer",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "2w ago",
    "contract": "Full Time",
    "location": "USA Only",
    "languages": ["JavaScript"],
    "tools": ["Vue", "Sass"]
  },
  {
    "id": 9,
    "company": "Eyecam Co.",
    "logo": eyecamco,
    "new1": false,
    "featured": false,
    "position": "Full Stack Engineer",
    "role": "Fullstack",
    "level": "Midweight",
    "postedAt": "3w ago",
    "contract": "Full Time",
    "location": "Worldwide",
    "languages": ["JavaScript", "Python"],
    "tools": ["Django"]
  },
  {
    "id": 10,
    "company": "The Air Filter Company",
    "logo": the,
    "new1": false,
    "featured": false,
    "position": "Front-end Dev",
    "role": "Frontend",
    "level": "Junior",
    "postedAt": "1mo ago",
    "contract": "Part Time",
    "location": "Worldwide",
    "languages": ["JavaScript"],
    "tools": ["React", "Sass"]
  }
]

如果,我应该尝试将值存储在 useState 数组而不是普通数组中吗?

请帮我修正这个代码, 谢谢。

1 个答案:

答案 0 :(得分:0)

您应该使 arrIds 成为组件状态的一部分。

const App = () => {
  const [values, setvalues] = useState([]);
  const [ids, setids] = useState([]);

  const [arrIds, setArrIds] = useState([]); // <-- create arrIds state array

  ...

  useEffect(() => {
    arrValue = [];
    Menu.filter((x) => {
      ...
    });
    arrValue = [...new Set(arrValue)];

    if (arrValue) {

      setArrIds(arrIds => [...arrIds, ...arrValue]); // <-- shallow copy & append

      for (var a = 0; a < arrValue.length; a++) {
        ...
      }
    }
  }, [values]);
};