从 API 获得响应后更新 redux-thunk 中的局部变量的最佳实践是什么?



我已经实现了redux-thunk,它在我的反应原生应用程序中运行良好。我有一些"this.counterValue",在从 API 获得响应后必须更新该值。由于 api fetch 方法在另一个操作文件中实现,并且响应是在该文件中实现的。那么,必须如何实施才能使这项工作正常工作。我不希望"this.counterValue"中的更改导致我的应用程序重新呈现。我是本地人的新人,得到帮助会很棒。谢谢。

组件文件:

this.counterValue = 75; //local variable
this.props.fetchData('onStart'); // call to fetch data from actions files

操作文件:

export const fetchData = (fetchType) => {
return async dispatch => {
dispatch(fetchingDataRequest());
fetch(AllApi),
{
method: 'GET',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer '+ global.apiToken,
},
})
.then(response => {
return response.json()
})
.then(RetrivedData => {
dispatch(fetchingDataSuccess(RetrivedData.data));
})
.catch(error => {
dispatch(fetchingNotificationFailure(error));
});
}
}

使用调度将数据发送到化简器,并在化简器中更新状态值,然后您可以在组件中使用它。

还原剂

import { reducerWithInitialState } from 'typescript-fsa-reducers'
import { DemoListViewActions } from './Actions'
export interface DemoListViewState {
data: any[]
selectedData: any
}
const initialState: DemoListViewState = {
data: [],
selectedData: undefined
}
const dataListRequestSuccessHandler = (state: DemoListViewState, payload: any[]): DemoListViewState => {
return {
...state,
data: payload
}
}

export const DemoListViewReducer = reducerWithInitialState(initialState)
.case(DemoListViewActions.dataListRequestSuccess, dataListRequestSuccessHandler)
.build()

容器

const mapStateToProps: MapStateToProps<IDemoListViewStateProps, OwnProps, RootState> = (state: RootState, ownProps: OwnProps) => {
const {data} = state.demoListView
return {
listData: data
}
}

元件

export interface IDemoListViewStateProps {
listData: any[]
}

只需将其存储在道具和状态中,您就可以轻松操作它

调度操作后,您必须更新减速器

Import Action from './Action'
const initialState = { 
people :[  ] // initiate empty array
}
export default function(state=initialState,action){
switch(action.type){
case Action.test:
return testUpdate(state,action)
default :
return state
}
}
//Update the result from the api,people array will be populated 
with latest data
function testUpdate(state,action){
return {...state,people:action.payload.people}
}

最新更新