首先,我喜欢Meteor,但现在我正在学习React我想知道是否有可能像Meteor那样提取数据,只有React。关键是我有点极简主义,并希望在React周围尽可能少地使用更少的库/框架。
谢谢
答案 0 :(得分:1)
您不需要像Meteor这样的完整堆栈平台来从Web服务获取数据。您可以查看XMLHttpRequest(AJAX)。在使用纯JavaScript实现时,它看起来很奇怪,但是得到广泛支持。
另一个选项(我强烈建议)使用fetch。 Fetch是浏览器发出HTTP请求的本机方式。你甚至可以从获取中获得承诺的力量。但是,目前所有浏览器都不支持它,尤其是较旧的浏览器。
也许你可以使用像whatwg-fetch这样的polyfill来支持旧浏览器。
答案 1 :(得分:1)
最简单的方法是使用fetch。您还可以查看其他更多功能的选项,例如SuperAgent。这是一个结合了React和fetch的基本示例:
class Example extends React.Component {
constructor() {
super();
this.state = { user: {} };
}
componentDidMount() {
var self = this;
fetch('http://reqres.in/api/users/2')
.then(function(response) {
return response.json()
}).then(function(body) {
console.log(body.data);
self.setState({
user: body.data
});
});
}
render() {
return(
<div>{this.state.user.first_name} {this.state.user.last_name}</div>
);
}
}
ReactDOM.render(<Example/>, document.getElementById('View'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.min.js"></script>
<div id="View"></div>
&#13;
请注意,您可能需要添加polyfill for fetch,具体取决于您要支持的浏览器。
此处与SuperAgent的请求相同:
class Example extends React.Component {
constructor() {
super();
this.state = { user: {} };
}
componentDidMount() {
var self = this;
superagent
.get('http://reqres.in/api/users/2')
.end(function(err, res) {
console.log(res.body.data);
self.setState({ user: res.body.data })
});
}
render() {
return(
<div>{this.state.user.first_name} {this.state.user.last_name}</div>
);
}
}
ReactDOM.render(<Example/>, document.getElementById('View'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/superagent/2.3.0/superagent.min.js"></script>
<div id="View"></div>
&#13;