我现在在 React.js 组件中使用react-http-request 来发送请求并处理响应。传递的URL参数与组件状态相关,当状态改变时,组件将重新渲染并改变组件显示。
这适用于第一个请求。但是,我发现该组件在第二次请求后没有返回 {load: true},我想知道如何解决这个问题。
我尝试调用 onRequest 方法并设置组件的加载状态,但请求完成后无法更改加载状态(因为渲染函数无法更改状态)。
react-http-请求:https://github.com/mbasso/react-http-request
我的代码如下:
var FilmList = React.createClass({
getInitialState: function(){
return {
queryType: this.props.queryType
}
},
// ... details emitted.
render: function(){
return (<Request
url={config.url.api + "/" + this.state.queryType}
method="get"
accept="application/json"
query={{ several parameter }}
>
{
({error, result, loading}) => {
if (loading || error) {
return <Loading />
}
else {
// process the result here.
}
}
}
</Request>)
}
最佳答案
因此,我最初的建议是您使用一些状态管理库(redux、mobx 等),但没有必要获取代码的工作示例,因此:
import fetch from 'whatwg-fetch'; // gives compatibility with older browsers
var FilmList = React.createClass({
getInitialState: function(){
return {
queryType: this.props.queryType,
content: null
}
},
componentWillMount: function() {
this.fetchContent();
},
fetchContent: function() {
const uri = config.url.api + "/" + this.state.queryType;
// You can use w/e you want here (request.js, etc), but fetch is the latest standard in the js world
fetch(uri, {
method: 'GET',
// More properties as you see fit
})
.then(response => response.json()) // might need to do this ;)
.then(response => {
this.setState({
content: response
})
})
},
// ...
render: function(){
const content = this.state.content? (
// render your content based on this.state.content
): (
<Loading />
)
return content;
}
});
尚未测试此代码,但它有一些很好的好处:
- http 请求不依赖于 React,理论上应该是针对 UI 组件的。
- 获取机制是解耦的,可以在组件生命周期的任何时刻重用
- 我认为更容易阅读,分为更小的逻辑 block
我建议阅读 React Component Lifecycle .
关于javascript - 在第二次请求后,react-http-request 不会更改加载状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918931/