【问题标题】:exporting a variable from index.js and importing it into another class - react.js从 index.js 导出变量并将其导入另一个类 - react.js
【发布时间】:2021-04-16 19:52:21
【问题描述】:

我正在尝试在另一个类 util.js 中使用我的索引中的变量。在 index.js 的构造函数中,我将两个变量设置为 0,然后使用 this.setState({ startTime: Date.now() })this.setState({ endTime: Date.now() })。我看到一个建议在我的类上方的 index.js 上使用 export const difference = true;,然后在 render() 之后,在 return () 之前使用 const difference = this.state.endTime - this.state.startTime;。 从那里我想将它导入到我的 util.js 中,这样我就可以将它放在我的数据库中。

util.js:

import "isomorphic-fetch"
import { difference } from "../pages/index.js";

export function addName(name) {
    return fetch('http://localhost:3001/addtime', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, time: difference }) // getting errors with this
    })
}

App.js

import React from 'react';
import { addName } from "./util";

function App() {
  const [name, setName] = React.useState("")

  function handleUpdate(evt) {
    setName(evt.target.value);
  }

  async function handleAddName(evt) {
    await addName(name);
  }

  return <div>
    <p><input type='text' value={name} onChange={handleUpdate} /></p>
    <button className='button-style' onClick={handleAddName}>Add Name</button>
  </div>
}

export default App;

这样做会给我两个错误:UnhandledPromiseRejectionWarning 和 DeprecationWarning。 index.js:

export const difference = true;

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
         startTime: 0,
         endTime: 0,
    };
   }
  handleStart = () => {
    ...
    this.setState({
      startTime: Date.now()
    })
    ...
  }
  handleStop = () => {
    ...
    this.setState({
      endTime: Date.now()
    })
    ...
  }

  render() {
    const difference = this.state.endTime - this.state.startTime;
    return (
    ...
    )
  }
}

我的主要问题是,如何从我在构造函数中设置的主类中导出一个变量,然后将其导入另一个类,然后从那里将其放入数据库中?

【问题讨论】:

  • 差异应该代表什么?是他们启动应用的时间吗?
  • 我构建了一个秒表,然后我希望用户能够将他们的时间存入数据库。所以,我设置了 startTime 和 endTime,然后用 startTime 减去 endTime。然后我想把我得到的东西放到数据库中。

标签: javascript reactjs postgresql


【解决方案1】:

我认为您无法导出该变量。 最好将该变量作为 props 传递或保存到 redux 中。

【讨论】:

    【解决方案2】:

    export 是顶级的,这意味着您不能从块内导出。您也无法重新初始化const,因此您阅读的建议不起作用。您可以在index.js 的顶部将其初始化为export let difference,然后在您的渲染函数中初始化difference = this.state.endTime - this.state.startTime。但是以这种方式传递类组件状态是非常尴尬的。一个好的解决方案是考虑使用 Redux 或 React.Context。这将允许您存储difference,然后将其拉出到您调用addNameApp.js

    【讨论】:

      【解决方案3】:

      虽然您尝试做的事情是可能的,但它会出现错误且难以维护。

      在 React 中,所有数据都应该作为 props 传递。这保证了组件将被正确更新并相应地重新渲染。访问普通的共享变量将在渲染周期之外,并可能导致问题或意外结果。

      在 react 中有 2 种方法可以做到这一点:Prop 传递和 Context。上下文可能不是这里的正确工具。上下文通常用于防止 prop 钻取(即,将 props 从顶部组件向下传递到几个不同的组件)或者如果有多个具有特定值的消费者。请参阅注意事项here

      在这种情况下,您可以相当简单地传递它,我建议将一个函数传递给 StopWatch 类(在您的示例中为 Home)


      使用道具

      App.js

      import React from 'react';
      import StopWatch from './StopWatch';
      import { addName } from "./util";
      
      function App() {
        const [name, setName] = React.useState("")
        const [duration, setDuration] = React.useState(0)
      
        function handleUpdate(evt) {
          setName(evt.target.value);
        }
      
        async function handleAddName(evt) {
          await addName(name, duration);
        }
      
        return <div>
          <StopWatch onStop={(d) => setDuration(d)} />
          <p><input type='text' value={name} onChange={handleUpdate} /></p>
          <button className='button-style' onClick={handleAddName}>Add Name</button>
        </div>
      }
      
      export default App;
      

      StopWatch.js

      export default class StopWatch extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
               startTime: 0,
          };
         }
        handleStart = () => {
          ...
          this.setState({
            startTime: Date.now()
          })
          ...
        }
        handleStop = () => {
          const difference = Date.now() - this.state.startTime;
          this.props.onStop(difference);
          ...
        }
      
        render() {
          return (...)
        }
      }
      

      注意:您还必须修改 addName 函数以接受差异作为参数。

      【讨论】:

        猜你喜欢
        • 2019-08-23
        • 2018-04-28
        • 2020-12-18
        • 1970-01-01
        • 1970-01-01
        • 2019-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多