如何在react-redux中发出HTTP请求?
我才刚开始做出反应,我有点迷茫.我正在尝试制作一个登录页面并发出一个http发布请求.现在,我只是想使任何类型的HTTP请求都能正常工作,所以我使用了请求bin,我在文档中找到了一个针对npm包的基本操作(
I am just getting started with react and I'm a bit lost. I'm trying to make a login page and make a http post request. Right now I'm just trying to get any type of HTTP request working, so I'm using request bin and I found this basic action in the docs for an npm package (https://www.npmjs.com/package/redux-react-fetch):
export function updateTicket(ticketId, type, value){
return {
type: 'updateArticle',
url: `http://requestb.in/1l9aqbo1`,
body: {
article_id: ticketId,
title: 'New Title'
},
then: 'updateTicketFinished'
}
}
那么,写完一个动作后,我该怎么办?我实际上如何让我的应用程序调用并使用该操作? npm软件包的文档中提到了有关在商店中设置状态的内容,这是我需要首先设置的内容吗?
So, after writing an action, what do I do? How do I actually get my app to call on and use that action? The docs for the npm package mention something about setting a state in my store, is that something I need to set up first?
您可以尝试以下任何一种方法.我同时使用了fetch
和axios
,它们的表现都非常好.尚未尝试superagent
.
You can try any of the following. I have used both fetch
and axios
they work amazingly well. Yet to try superagent
.
- For making requests you can either use
fetch
with fetch-polyfill for compatibility across all browsers (link) - Axios library. (link)
- Superagent with promises.(link)
如果使用访存,则需要使用polyfill,因为IE和Safari浏览器尚不支持它.但是使用polyfill可以很好地工作.您可以查看链接以了解如何使用它们.
If you use fetch you would need to use polyfill since it is not supported in IE and safari yet. But with polyfill it works pretty well. You can check out the links for how you can use them.
因此,您要做的就是在动作创建器中使用上述任何一种来调用API.
So what you would doing is in your action creator you can call an API using any of the above.
FETCH
function fetchData(){
const url = '//you url'
fetch(url)
.then((response) => {//next actions})
.catch((error) => {//throw error})
}
AXIOS
axios.get('//url')
.then(function (response) {
//dispatch action
})
.catch(function (error) {
// throw error
});
那是为了API调用,现在进入状态.在redux中,有一种状态可以处理您的应用.我建议您应该在此处中找到redux的基础知识.因此,一旦您的api调用成功,您就需要使用数据更新状态.
So that was for the API call, now coming to the state. In redux there is one state which handles your app. I would suggest you should go through redux basics which you can find here . So once your api call succeeds you need to update your state with the data.
获取数据的操作
function fetchData(){
return(dispatch,getState) =>{ //using redux-thunk here... do check it out
const url = '//you url'
fetch(url)
.then (response ) => {dispatch(receiveData(response.data)} //data being your api response object/array
.catch( error) => {//throw error}
}
}
更新状态的动作
function receiveData(data) {
return{
type: 'RECEIVE_DATA',
data
}
}
减速器
function app(state = {},action) {
switch(action.types){
case 'RECEIVE_DATA':
Object.assign({},...state,{
action.data
}
})
default:
return state
}
}