jmo*_*789 17 jsx reactjs redux react-redux
我刚开始反应,我有点迷失.我正在尝试创建登录页面并发出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'
}
}
Run Code Online (Sandbox Code Playgroud)
所以,在写完一个动作之后,我该怎么办?我如何实际让我的应用程序调用并使用该操作?npm包的文档提到了在我的商店中设置状态的东西,我需要先设置一些东西吗?
Har*_*uja 35
您可以尝试以下任何一种方法.我已经使用过它们fetch
并且axios
它们的工作效果非常好.然而试试superagent
.
如果你使用fetch,你需要使用polyfill,因为IE和safari还不支持它.但是使用polyfill它可以很好地工作.您可以查看链接以了解如何使用它们.
那么你要做的就是在你的动作创建者中,你可以使用上述任何一种方法调用API.
取
function fetchData(){
const url = '//you url'
fetch(url)
.then((response) => {//next actions})
.catch((error) => {//throw error})
}
Run Code Online (Sandbox Code Playgroud)
AXIOS
axios.get('//url')
.then(function (response) {
//dispatch action
})
.catch(function (error) {
// throw error
});
Run Code Online (Sandbox Code Playgroud)
那就是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}
}
}
Run Code Online (Sandbox Code Playgroud)
更新状态的行动
function receiveData(data) {
return{
type: 'RECEIVE_DATA',
data
}
}
Run Code Online (Sandbox Code Playgroud)
减速器
function app(state = {},action) {
switch(action.types){
case 'RECEIVE_DATA':
Object.assign({},...state,{
action.data
}
})
default:
return state
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28478 次 |
最近记录: |