简体   繁体   English

如何在单独的 .js 文件上的 React 应用程序中共享变量?

[英]How can I share variables across a react application on separate .js files?

I have a series of forms that should build on one another, without having to ask the same questions over again.我有一系列的表格应该相互建立,而不必再问同样的问题。 This is analogous to session variables in PHP.这类似于 PHP 中的会话变量。

I looked into props, state, effect, and the styles library but nothing seems to work.我查看了道具、状态、效果和样式库,但似乎没有任何效果。

Also note: I have all my create react app one one js file (as a class.extends..., not an arrow function const), my functions on another js file, and my UI on yet another js file all in the main directory.另请注意:我所有的 create react 应用程序都是一个 js 文件(作为 class.extends ...,而不是箭头函数 const),我在另一个 js 文件上的函数,以及我在另一个 js 文件上的 UI 都在主文件中目录。

Does everything have to be in the App.js file or is there a way to modify central variables from the functions ie (App.firstName = this.fname) or similar to state:是否所有内容都必须在 App.js 文件中,或者有没有办法修改函数中的中心变量,即 (App.firstName = this.fname) 或类似于状态:

const reluctantVariableNameToAvoidErrors () => setState( App.firstName : fname );常量不情愿变量名避免错误() => setState( App.firstName : fname );

This seems to not throw errors but is unreadable by a separate export const function.这似乎不会引发错误,但无法通过单独的导出 const 函数读取。

This is the starting form where it takes info and calls a query (this works):这是获取信息并调用查询的起始形式(这是有效的):

export const home = (props) => (
    <div className="App">
        <div className="App-header">
            <img src={"./dgsl.png"} width={"400px"} alt="logo" />
            <br/><h2>Welcome</h2><br/>
            <Input id="oldtele" className="w-25" placeholder="Existing Telephone">t</Input><br/>
            <Button onClick={() => queryGuest(document.getElementById("oldtele").value)}>I am a Returning Visitor</Button><br/>
            <Link href={"./enroll"}  onlyActiveOnIndex>I am a new Guest</Link>
        </div>
    </div>
);

That calls this function sending the info as a prop or parameter (i'm not sure):调用此函数将信息作为道具或参数发送(我不确定):

export function queryGuest(ot) {
    const telRef = db.collection("guests");
    const that = this;
    const query = telRef.where("telephone", "==", ot)
        .get()
        .then(function (querySnapshot) {
            querySnapshot.forEach(function (doc) {
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data());
                const fnameR = doc.get("fname");
                const lnameR = doc.get("lname");
                const teleR = doc.get("telephone");
                const employR = doc.get("employer");
                const lictypR = doc.get("licType");
                const licnoR = doc.get("licNo");
                    alert(fnameR + " " + lnameR + " found in system.");
                        let set = () => this.setState({fname: fnameR});
                        set = () => this.setState({lname: lnameR});
                        set = () => this.setState({tele: teleR});
                        set = () => this.setState({employ:employR});
                        set = () => this.setState({licTyp:lictypR});
                        set = () => this.setState({licNo:licnoR});
                questions(fnameR);
                window.location.href = "./questions";

            })
        });
}

Should change the variables here in App:应该在 App 中更改此处的变量:

import { home, newguest, thankyou, questions } from './pages';从'./pages'导入{家,新来者,谢谢,问题};

class App extends React.Component {
    constructor(props) {
        super(props);

        const [state, setState] = useState({
            fname: "na",
            lname: "na",
            tele: "na",
            employ: "na",
            resid: "na",
            room: "na",
            reason: "na",
            instr: "na",
            nextvis: "na",
            nodays: "na",
            cov: "na",
            lictype: "na",
            licno: "00"
        });

    }

        render() {
            return (
                <Router history={browserHistory}>
                    <Route path="/" component={home}/>
                    <Route path="/enroll" component={newguest}/>
                    <Route path="/thanks" component={thankyou}/>
                    <Route path="/questions" component={questions}/>
                </Router>
            );
        }
    }

And then be retrievable later here without needing to be re-entered and passes as a parameter:然后可以稍后在此处检索而无需重新输入并作为参数传递:

export function addVisit() {
    //disburses all state variables to the visits table in db
    db.collection("visits").add({
        date: Date.now.toString(),
        guestfname: this.state.fname,
        guestlname: this.state.lname,
        telephone: this.state.tele
    }).then(r => r => window.location.href = "./thanks");
}

So is there some special library i need, or do i need to do mount lifecycles or should i just try to design it to be very one-way so they have to enter everything on the same page and send it all from function to function?那么我是否需要一些特殊的库,或者我是否需要进行挂载生命周期,或者我应该尝试将它设计为非常单向的方式,以便他们必须在同一页面上输入所有内容并将其从功能发送到功能?

Furthermore, should it be set up so that the functions are attached to the rendered UI as a return()?此外,是否应该设置为将函数作为 return() 附加到呈现的 UI 上? I like having them separate but everything i see online has them attached.我喜欢把它们分开,但我在网上看到的所有东西都附有它们。

Thanks!谢谢!

to start off you are using useState in a class component.首先,您在类组件中使用useState You can't do that, hooks are meant for function components, a class component has this.state and this.setstate .你不能那样做,钩子是用于函数组件的,一个类组件有this.statethis.setstate For sharing state across multiple files you probably want to look into the context API .要在多个文件之间共享状态,您可能需要查看上下文 API you would define your state in the app and pass that state the value of a Context.Provider which you have as a parent for all the other components.您将在应用程序中定义您的状态并将该状态传递给您作为所有其他组件的父级的Context.Provider的值。 within the function components, you can access the state by using the useContext hook在函数组件中,您可以使用useContext钩子访问状态

So it turned out there were a few solutions, the simplest being useState.所以结果证明有几个解决方案,最简单的是 useState。

This was done by instantiating the state in App.js and then passing the state variable and it's alteration function to each of the components that need it.这是通过在 App.js 中实例化状态然后将状态变量及其更改函数传递给需要它的每个组件来完成的。 Those functions in turn make the calls back to their source.这些函数反过来使调用返回到它们的源。

EXAMPLE:例子:

const App = () => {
const [cars, setCars] = useState({object or array});

return(
   <Router>
    <Route path='/make'><makeCars carslist={cars} changecars={setCars}/>{</Route>
    <Route path='/viewonly'><viewCars carslist={cars}/></Route>
   </Router>
)
}

And then in the other function where you want to access it:然后在您要访问它的另一个函数中:

export const makeCars = ({ changeCars, carslist }) => {
//make the 'cars' object in App.js become equal to "corvette"
changeCars("corvette");
}

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

相关问题 我们可以在不使用 require 或 module.exports 的情况下跨 js 文件共享全局变量吗? - Can we share the global variables across js files without using require or module.exports? 如何在反应应用程序中共享 class 实例? - How to share a class instance across a react application? 如何使用 Node.js 制作应用程序,它可以分隔所有具有相同扩展名的文件? - How can i make an application using Node.js, which can separate all the files with same extension? React.js:如何使用两个不同的独立 Button 组件下载两个不同的文件? - React.js: How can I download two different files with two different separate Button components? 如何在页面之间共享JS变量? - How can I share JS variables between pages? 如何在 js 中全局使用变量(跨多个文件)? - How can I use a variable globally in js (across many files)? 如何在Vue.js应用程序中共享“计算”方法 - How to share “computed” methods across a Vue.js application 如何在Node JS中的不同文件之间共享一个数据库连接? - How to share one database connection across different files in node js? 我可以在 React 中跨多个树共享一个组件实例吗? - Can I share a component instance across multiple trees in React? 如何将JS和CSS拆分为单独的HTML文件? - How can I split the JS and CSS into separate HTML files?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM