Nik*_*eke 3 javascript react-native fetch-api
对不起标题中的笑话.
我目前正在探索反应原生的fetch API,但我遇到了一些我无法解决的问题.
所以,我试图从服务器获取一条消息,我用以下方式使用fetch API调用它:
var serverCommunicator = {
test: function() {
fetch(baseUrl , {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then((response) => response.text())
.then((responseText) => {
return (JSON.stringify(responseText));
})
.catch((error) => {
console.warn(error);
}).done();
},
module.exports = serverCommunicator;
Run Code Online (Sandbox Code Playgroud)
当我仅使用console.log(responseText)我的日志测试时给了我正确的消息.但是,现在当我想尝试将代码中的内容作为消息放入View中时,它不会按预期返回.以下列方式调用它:
import Method from '../Services/Methods';
.
.
.
<View style={styles.card}>
<CardView
message={Method.test()}
/>
Run Code Online (Sandbox Code Playgroud)
我可以看到在调用它时如何正确调用函数测试,但由于某种原因,它不会编写消息.
这是一个经典的异步问题,你的then函数在render被调用之后返回,无处可return去.
最常见的解决方案:显示空状态消息/加载指示器,并在组件安装时获取服务器信息.当您的promise返回并then触发回调时,请设置将触发重新呈现的组件状态以及您的预期值.
class extends React Component
class YourComponent extends Component {
constructor() {
super()
this.state.text = 'Loading, please wait!' // default text
}
componentDidMount() {
fetch(baseUrl, options)
.then((response) => response.text())
.then((responseText) => {
this.setState({ text: responseText }) // this triggers a re-render!
})
}
render() {
return (
<View style={styles.card}>
<CardView
message={this.state.text} // <-- will change when fetch call returns
/>
</View>
)
}
}
Run Code Online (Sandbox Code Playgroud)
React.createClass
var YourComponent = React.createClass({
getInitialState() {
return { text: 'Loading, please wait!' }
}, // <-- comma between functions, because object keys
componentDidMount() {
fetch(baseUrl, options)
.then((response) => response.text())
.then((responseText) => {
this.setState({ text: responseText }) // this triggers a re-render!
})
},
render() { /* ..same as above.. */ }
})
Run Code Online (Sandbox Code Playgroud)
如果要将当前体系结构保留在服务中的提取调用中,则需要将初始调用返回到fetch,这将返回一个promise.然后你可以then在你的构造函数中连接:
var serverCommunicator = {
test: function() {
return fetch(baseUrl, options) // return a promise! ..important!
.then((response) => response.text())
.then((responseText) => {
return responseText
})
}
}
Run Code Online (Sandbox Code Playgroud)
然后导入的函数将返回一个承诺..
import Method from '../Services/Methods'
...
componentDidMount() {
Method.test().then(responseText => {
this.setState({ text: responseText })
})
]
....
Run Code Online (Sandbox Code Playgroud)
希望能够清楚地了解Promises如何工作,以及如何state在React中使用异步数据进行捕获!
| 归档时间: |
|
| 查看次数: |
4014 次 |
| 最近记录: |