fetch 我看官网的介绍的原声写法,但是在reactjs 之中我不知道怎么写,诸位有没有demo可以参考一下的呀
React 之中fetch 应该怎么写
OshotOkill
#7
之前ajax怎么用fetch就怎么用,react里面一般都写在componentDidiMount
里面, 当然也可以写入redux的 actionCreator
componentDidMount() {
fetch('path').then()
}
haishanh
#8
应该就是
npm install --save isomorphic-fetch es6-promise
然后
class Element extends Component {
componentDidMount = () => {
fetch('url-xxx')
.then(res => res.json())
.then(this.setState({
//...
}););
}
render = () => {
// return (...);
}
}
吧
Miao.Miracle
#10
亲测过的写法如下:
get请求的时候
fetch(‘MYURL’).
then(res=>res.json()).
then(json=>dispatch(myActionName(json))).
catch(err=>dispatch(myErrActionName(err)));
POST请求的时候
fetch(‘URL’,
{
method:‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’
},
body:JSON.stringify({‘data’:json})
}
)
.then(res => res.json())
.then(json =>dispatch(receivePosts(json)))
.catch(error=>dispatch(requestExceptions(error)));
JSON.stringify这个很重要,否则我们的数据无法被识别为json会很痛苦。希望对您的开发有帮助
2 Likes
benzeph
#14
你的问题应该是怎么把fetch引入到webpack打包的结果中吧?
参考这里:
或者你可以用这个 Promise库来做,不需要在webpack里面配置polyfill,直接用require或者import