gpt4 book ai didi

javascript - 如何在 React with Redux 项目中实现用于 API 服务调用的动态 reducer 创建器?

转载 作者:行者123 更新时间:2023-11-27 22:30:22 24 4
gpt4 key购买 nike

由于我可能有很多API服务要调用,我必须为这些服务编写尽可能多的reducer,有没有办法像下面这样动态地实现reducer创建者?

const PENDING = 'PENDING'
const REJECTED = 'REJECTED'
const FULFILLED = 'FULFILLED'
const COMPANIES = 'COMPANIES'

let createReducer = (name) => (state, action) => {
switch (action.type) {
case name + '_' + PENDING:
return {...state,
isLoading: false
}
case name + '_' + FULFILLED:
return {...state,
companies: action.payload,
isLoading: false
}
case name + '_' + REJECTED:
return {...state,
isLoading: false,
err: action.payload
}
default:
return state
}
}

let comapnyReducer = createReducer(COMPANIES)

这可以等价于下面的显式实现:

const comapnyReducer = (state={isLoading: false}, action) => {
switch (action.type) {
case 'COMPANIES_PENDING':
return {...state,
isLoading: false
}
case 'COMPANIES_FULFILLED':
return {...state,
companies: action.payload,
isLoading: false
}
case 'COMPANIES_REJECTED':
return {...state,
isLoading: false,
err: action.payload
}
default:
return state
}
}

最佳答案

此示例的目的是说明它可能是怎样的。您的实现在细节上可能有所不同。

DEMO JSBIN

const PENDING = 'PENDING'
const REJECTED = 'REJECTED'
const FULFILLED = 'FULFILLED'

const reducer = (state={isLoading:false}, action) => {
const {name, type} = action;
switch (type) {
case name + '_' + PENDING:
return {...state, isLoading: false }
case name + '_' + FULFILLED:
return {...state,
items: action.payload,
isLoading: false
}
case name + '_' + REJECTED:
return {...state,
isLoading: false,
err: action.payload
}
default:
return state
}
}

const entities = (state={},action)=>{
if(action.name){
const name = action.name.toLowerCase()
return {...state, [name]:reducer(state[name],action) }
}else{
return state
}
}

Action 示例

{type:'COMPANIES_FULFILLED',name:'COMPANIES',payload:[1,2,3,4]}

结果

    "companies": {
"items": [
1,
2,
3,
4
],
"isLoading": false
},
"messages": {
"items": [
1,
2,
3,
4
],
"isLoading": false
}

关于javascript - 如何在 React with Redux 项目中实现用于 API 服务调用的动态 reducer 创建器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39645533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com