我现在在React.js组件中使用react-http-request发送请求并处理响应。传递的URL参数与组件状态相关,这样,当状态更改时,将重新呈现组件并更改组件显示。
这适用于第一个请求。但是,我发现该组件在第二个请求之后没有返回{load:true},并且我想知道如何解决这个问题。
我试图调用onRequest方法并设置组件的加载状态,但是在请求完成后我无法更改加载状态(因为render函数无法更改状态)。
react-http-request: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组件。
提取机制已解耦,并且可以在组件生命周期中的任何时候重用
我认为更容易阅读,分为较小的逻辑块
我建议阅读React Component Lifecycle。
关于javascript - 第二次请求后react-http-request不会更改加载状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41918931/