我刚开始反应,我有点迷失。我正在尝试创建一个登录页面并发出http post请求。现在我只是想让任何类型的HTTP请求工作,所以我正在使用请求bin,我在npm包的文档中找到了这个基本动作(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包的文档提到了在我的商店中设置状态的东西,我需要先设置一些东西吗?
您可以尝试以下任何一种方法。我用过这两个 fetch
和 axios
他们工作得非常好。然而试试 superagent
。
- 要提出请求,您可以使用
fetch
同
fetch-polyfill兼容所有浏览器(链接)
- Axios库。 (链接)
- 超级承诺。(链接)
如果你使用fetch,你需要使用polyfill,因为IE和safari还不支持它。但是使用polyfill它可以很好地工作。您可以查看链接以了解如何使用它们。
那么你要做的就是在你的动作创建者中你可以使用上面的任何一个来调用API。
取
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调用成功,您需要使用数据更新您的状态。
获取数据的操作
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
}
}