简体   繁体   English

如何在 React JS 中访问另一个文件(和函数)的 state?

[英]How can I access a state of another file (and function) in React JS?

I'm looking for a solution for my problem.我正在为我的问题寻找解决方案。 I'm using a library called unstated ( https://github.com/GitbookIO/unstated ).我正在使用一个名为 unstated 的库( https://github.com/GitbookIO/unstated )。 It makes a global state for an reactjs app.它为 reactjs 应用程序生成全局 state。 The problem is: I can't use a state made on a function X in my function Y. In this case, I created my state in App.js and wanna access it in my DivCheckBox.js. The problem is: I can't use a state made on a function X in my function Y. In this case, I created my state in App.js and wanna access it in my DivCheckBox.js.

App.js:应用程序.js:

    import './App.css';
import DivCheckBox from './components/DivCheckBox/DivCheckBox';
import { Container, useUnstated } from '@gitbook/unstated';

class DadosUnstated extends Container<{
  nodesPadrao: Object,
  edgesPadrao: Object,
  }> {
  state = {
    nodesPadrao: [
      {
        status: 0,
        id:1,
        label: 'MAT001',
        title: 'CALCULO DIFERENCIAL E INTEGRAL I',
        details: "Integrais- impróprias: seqüências séries numéricas. Funções de R em R. Derivadas. Integrais. Aplicações. \"Regras de L'Hospital\".",
        level: 1,
        weight: 90,
        groupId: 1,
        subGroupId: 1,
        slots: [1, 2],
      },
      {
        status: 0, 
        id:50,
        label: 'EEE019',
        title: 'TRABALHO DE CONCLUSAO DE CURSO II',
        details: 'Finalização do projeto elaborado, no projeto final de curso I e apresentação de monografia. Defesa do trabalho perante banca examinadora.',
        level: 11,
        weight: 90,
        groupId: 5,
        subGroupId: 4,
        slots: [1, 2],
      },
      {
        status: 0, 
        id:51,
        label: 'EEE020',
        title: 'ESTAGIO SUPERVISIONADO EM ENGENHARIA DE SISTEMAS',
        details: 'Atividades de treinamento, supervisionadas por um docente do curso, na área de atuação profissional do engenheiro de sistemas.',
        level: 12,
        weight: 165,
        groupId: 5,
        subGroupId: 4,
        slots: [1, 2],
      },
    ],

    edgesPadrao:[
      {
        id: 1,
        from: 1,
        to: 7,
        label: 'MAT001 -> MAT039',
      },
      {
        id: 29,
        from: 32,
        to: 41,
        label: 'ELEXXE -> ELEXXF',
      },
      {
        id: 30,
        from: 44,
        to: 42,
        label: 'ELE090 -> ELEXXG',
      },
      {
        id: 31,
        from: 40,
        to: 41,
        label: 'ELEXXF -> ELE088',
      },
      {
        id: 32,
        from: 30,
        to: 42,
        label: 'ELT080 -> ELEXXG',
      },
      {
        id: 33,
        from: 35,
        to: 40,
        label: 'ELE077 -> ELE088',
      },
      {
        id: 55,
        from: 11,
        to: 33,
        label: 'ELEXXI -> ELEXXJ',
      },
      {
        id: 56,
        from: 47,
        to: 48,
        label: 'ELEXXK -> ELE087',
      },
    ],

  };
 
  increment(id) {
    let aux=this.state.nodesPadrao;
    aux[id-1].status=!aux[id-1].status;
    this.setState({ nodesPadrao: aux });
    console.log(this.state.nodesPadrao);
  }
 
  decrement(id) {
    let aux=this.state.nodesPadrao;
    aux[id-1].status=!aux[id-1].status;
    this.setState({ nodesPadrao: aux });
    console.log(this.state.nodesPadrao);
  }

}

function App() { function 应用程序(){

  const dados = useUnstated(DadosUnstated);

  return (
    <div>

              {dados.state.nodesPadrao.map(p => {
              return (
                
                <DivCheckBox nomeDisciplina = {p.title} labelDisciplina = {p.label} id = {p.id}/>
                
              )})
              }

            <p>{dados.state.edgesPadrao[3].status} oiiiiii {dados.state.edgesPadrao[0].status}</p>

    </div>
  );
}

export default App;

DivCheckBox.js:

    import React, { Component } from 'react';
import Func from './func'
import { Container, useUnstated } from '@gitbook/unstated';
import DadosUnstated from 'C:/Users/decyf/Desktop/PDEG/pdeg/src/App.js'

function DivCheckBox(props){

    const dados = useUnstated(DadosUnstated);

    dados.nodesPadrao[2].status=12;

    return(
          <div>
          <p id = "pgh">{props.nomeDisciplina}</p>
          <input id="MAT001" class = {props.labelDisciplina} type="checkbox" onClick={() => Func(props.labelDisciplina,props.id)}/>
          </div>
    );
    
}

export default DivCheckBox;

Func.js:函数.js:

    import { Container, useUnstated } from '@gitbook/unstated';
import DadosUnstated from 'C:/Users/decyf/Desktop/PDEG/pdeg/src/App.js'

function Func(classe,id){

    const dados = useUnstated(DadosUnstated);

    var chb = document.getElementsByClassName(classe);

    if(chb[0].checked){
        console.log("marquei o "+classe);
        
    }else if(!chb[0].checked){
        console.log("desmarquei o "+classe);
        
    }

}

export default Func;

Issue问题

I think you've mixed up what you are exporting from App.js and importing for use in DivCheckBox .我认为您已经混淆了从App.js导出的内容和导入以供在DivCheckBox中使用的内容。

In App.js :App.js

export default App;

In DivCheckBox.js :DivCheckBox.js

import DadosUnstated from 'C:/Users/decyf/Desktop/PDEG/pdeg/src/App.js';

...

const dados = useUnstated(DadosUnstated);

Here DadosUnstated is default imported from App.js , which is the App React component, not the DadosUnstated container that was defined.这里的DadosUnstated是默认从App.js导入的,它是App React 组件,而不是定义的DadosUnstated容器。

Solution解决方案

I think you probably exported DadosUnstated as a names export我认为您可能将DadosUnstated导出为名称导出

export DadosUnstated;

So you should import it as a named import因此,您应该将其作为命名导入导入

import { DadosUnstated } from 'C:/Users/decyf/Desktop/PDEG/pdeg/src/App.js';

I believe it will now reference the object you are expecting it to reference, ie the container, and the hook should now work.我相信它现在将引用您期望它引用的 object,即容器,并且钩子现在应该可以工作了。

const dados = useUnstated(DadosUnstated);

暂无
暂无

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

相关问题 我如何访问另一个js文件中的React Hook中完成的状态值 - How can I access a state value done in react hooks in another js file React - 如何访问不同 .js 文件中的一个 .js 文件中的状态/数组? - React - How can I access a state/array that's in one .js file in a different .js file? 如何访问 index.js 文件中的 react redux state? - How can I access react redux state in index.js file? 如何在另一个文件中的 function 中访问 state - How to access state in function which is in another file 我如何在另一个文件 js ANGULARJS 中调用函数 js - how can i call function js in another file js ANGULARJS 如何在 react.js ZA2F2ED4F8EBC2ABC61ZDC4 中的另一个 function 组件中设置相同的 state 变量后立即访问 state 值 - how to access state value right after setting the same state variable in another function in react.js class component 如何在React JS中的另一个函数中使用函数的状态或道具 - How to use state or props of a function in another function in react js 如何将状态值从一个组件访问到单独文件中的其他函数(而非组件)? React JS - How to access state value from one component to other function(not component) which is in separate file? React js 如何将数据从一个 js 文件访问到另一个文件? - How can I access data from one js file to another? 为什么我无法从另一个.js文件访问.js文件中定义的JavaScript函数? - Why I can't access a JavaScript function defined in a .js file from another .js file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM