我是 ReactJS 的新手,并且有点理解这个问题与 SOF 中的数字问题重复。
但我希望有人能给我一些关于 React 概念的指导和澄清。
我想要做的只是使用axios
或isomorphic-fetch
在加载屏幕之前从远程 REST API 获取数据。
但是,我看到了很多类似的 React 教程,我仍然没有明白这一点。
这是我的代码:
import React, { Component } from 'react';
import axios from 'axios'
// import InputRow from './components/InputRow';
import './App.css';
// require('es6-promise').polyfill();
// require('isomorphic-fetch');
class App extends Component {
constructor(props) {
super(props);
const app_id = '<my_app_id>';
const version = 0.1;
this.luisURL = `https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/${app_id}/versions/${version}`;
// this.getLUISIntent = this.getLUISIntent.bind(this);
this.state = {
intentOptions: [],
utterance: '',
intent: ''
};
}
getLUISIntent = () => {
const subscription_key = '<my_subscription_key>';
const URL = this.luisURL + '/intents';
return axios.get(URL, {
headers: {
"Content-Type": 'application/json',
"Ocp-Apim-Subscription-Key": subscription_key
},
})
.then(function(res){
this.setState({intentOptions: res.data});
});
}
componentWillMount = () => {
// this.setState({
// intentOptions: this.getLUISIntent()
// });
}
componentDidMount = () => {
this.getLUISIntent();
}
componentDidUpdate = (prevProps, prevState) => {
console.log("state: ", this.state);
// this.submitToLUIS();
}
shouldComponentUpdate = (nextProps, nextState) => {
return true;
}
submitToLUIS = () => {
console.log("Submit to LUIS: ", this.state);
};
setIntent = (e) => {
this.setState({intent: e.target.value});
};
setUtterance = (e) => {
this.setState({utterance: e.target.value});
};
render() {
return (
<div className="App">
<div className="container">
<div className="row">
<div className="col-sm-4">Utterance</div>
<div className="col-sm-4">Intent</div>
<div className="col-sm-4"></div>
</div>
<div className="row">
<div className="col-sm-4">
<input className="form-control utterance" type="text" onChange={this.setUtterance} />
</div>
<div className="col-sm-4">
<select className="form-control intent" onChange={this.setIntent}>
<option key="intent_defualt" value="">Select...</option>
{this.state.intentOptions.map((obj, i) =>
<option key={obj.id} value={obj.id}>{obj.name}</option>
)}
</select>
</div>
<div className="col-sm-4">
<button className="btn btn-primary" onClick={this.submitToLUIS}>Create</button>
</div>
</div>
</div>
</div>
);
}
}
export default App;
以下是我的问题:
- 我想在显示整个 UI 之前加载列表,这段代码中缺少什么?
- 在这里使用箭头功能是否正确
getLUISIntent
? - 我可以用
async/await
在getLUISIntent()
吗? - 对我来说,
async/await
意味着在执行下一个“行”之前等待函数的响应。这个概念正确吗? - 如果我需要写一个额外
this.__my_fancy_function__ = this.__my_fancy_function__.bind(this)
的使用类函数,使用箭头函数似乎写的代码更少,更易读,为什么不是每个人都使用它? - 那里有
Fetch remote API before loading anything using ReactJS tutorial no splitting different component but showing everything in only single App.js No BS so that everyone can see how a REST API-simple ReactJS app is run
教程吗?如果没有这样的东西,我想写它。但在此之前,我希望有人能先帮助我理清思路。
非常感谢您的帮助。