【发布时间】: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