React 之中fetch 应该怎么写

#1

fetch 我看官网的介绍的原声写法,但是在reactjs 之中我不知道怎么写,诸位有没有demo可以参考一下的呀

#2

阮一峰老师的教程:JavaScript 标准参考教程 AJAX Fetch

#3

文档我看得懂,就是不明白react之中该如何引用fetch

#4

浏览器大多不支持,可以用这个库 isomorphic-fetch

#5

这个我看到了,文档都是通用的写法,我在react 文件中具体如何写确实不明白,还望指点:grin:

#6

React docs - Load Initial Data via AJAX,把 $.get() 换成 fetch 就是了。

#7

之前ajax怎么用fetch就怎么用,react里面一般都写在componentDidiMount 里面, 当然也可以写入redux的 actionCreator

componentDidMount() {
  fetch('path').then()
}
#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 (...);
  }
}

#9

最好看下浏览器支不支持fetch,不支持的话再用其他的库去解决兼容性问题

#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
#11

看你的情况需求,get或者post方式,参考http://reactnative.cn/docs/0.28/network.html#content

#12

cFetch demo

看下这个是否有帮助~

#13

参考这里,项目实现经验 http://www.icafebolger.com/reactjs/reactfetch.html

#14

你的问题应该是怎么把fetch引入到webpack打包的结果中吧?

参考这里:

或者你可以用这个 Promise库来做,不需要在webpack里面配置polyfill,直接用require或者import