简体   繁体   English

如何访问全局 scope 中的 reactjs usestate 值?

[英]How to access reactjs usestate value in global scope?

I have the following reactJS code -我有以下 reactJS 代码 -

useEffect(()=>{
    const getinterviewerDetails= async ()=>{
      const data1 = await axios.get("http://localhost:8083/api/GetProduct")
      .then(response => {
        console.log("role is "+response.data[0].role)
        setinterviewerDetails(response.data)
        var cars = response.data,
        result = cars.reduce(function (r, a) {
            r[a.role] = r[a.role] || [];
            r[a.role].push(a);
            return r;
        }, Object.create(null));
        console.log("result is : ",result);
        console.log(interviewerDetails)
    })
    .catch(error => { console.log(error) })
    setinterviewerDetails(data1);
    };  
  getinterviewerDetails();
  },[])

From which I need to get the result value in the global scope, out of a useEffect function.从中我需要从useEffect function 中获取全局 scope 中的结果值。 I tried doing so just by declaring the variable from outside of the function scope and then initializing it from with useEffect scope.我尝试这样做只是通过从 function scope 外部声明变量,然后使用useEffect scope 对其进行初始化。 But, it was giving value as undefined.但是,它赋予了未定义的价值。 How can I get it done?我怎样才能完成它? I just need to access result value from global scope.我只需要从全局 scope 访问结果值。

I think one way is to create context ( https://en.reactjs.org/docs/hooks-reference.html#usecontext ) and put your variable inside of it.我认为一种方法是创建上下文( https://en.reactjs.org/docs/hooks-reference.html#usecontext )并将变量放入其中。

Other way is to declare your variable by useState in parent component and pass setState function to child component其他方法是在父组件中通过 useState 声明变量并将 setState function 传递给子组件

One way is to populate the window object.一种方法是填充 window object。 That is, to add result as a property to the window object.也就是说,将结果作为属性添加到 window object。 Since window is global, you will probably get the desired output.由于 window 是全局的,您可能会得到所需的 output。

window.result = result;

And then you could use it wherever you want, although I don't think there is an need to do this in React.然后你可以在任何你想要的地方使用它,尽管我认为在 React 中没有必要这样做。 You should try to use states and contexts rather than doing this while using React.你应该尝试使用状态和上下文,而不是在使用 React 时这样做。 Otherwise as @Lah Ezcen commented, you could also try using local storage.否则,正如@Lah Ezcen 评论的那样,您也可以尝试使用本地存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM