在我App.js
我有一个变量的状态,这:
App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
httpStatus: false
}
// react crap code below
render() {
return (
// blah blah blah blah components
);
}
}
然后,在中的子文件夹目录中src
,我有一个文件夹路径,fetch>updateHttp
其中包含一个名为javascript的文件updatehttp.js
,它仅具有一个需要编辑/更新该httpStatus
变量状态的函数(它只是一个函数,而不是类或组件):
更新http.js
updateHttp = () => {
this.setState({
httpStatus: true
})
export default updateHttp;
是否有一种简单的方法可以从App.js
此类的父类()中获取状态并仅从外部函数中对其进行更新?我不断在函数中遇到错误,no-undef
并且可以肯定它是因为this.setState...
该updateHttp
函数中的调用没有执行任何操作,因为它无法获取中存在的状态对象App.js
。
我最熟悉Backend Java,所以我是React的新手。
如果这是生产代码,则建议不要在App.js中使用业务/基础结构逻辑。
App.js
import React from 'react';
import GetResponseCode from "./GetResponseCode";
const App = () => {
return (
<>
<GetResponseCode/>
</>
);
}
export default App;
GetResponseCode.js
import React, {useState} from 'react';
import getDataFromAPI from './getDataFromAPI';
const GetResponseCode = () => {
const [responseCode, setResponseCode] = useState("")
const requestData = () => {
setResponseCode(getDataFromAPI());
}
return (
<div>
<h3>Response code: {responseCode} </h3>
<button onClick={requestData}>Get Data</button>
</div>
)
}
export default GetResponseCode;
getDataFromApi.js
const getDataFromAPI = () => {
//call the Api
//lines below just randomly simulate response code from Api
const httpCodes = ["200","400","404","500"];
return httpCodes[Math.floor(Math.random()*httpCodes.length)];
}
export default getDataFromAPI;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句