1

我已经实现了 redux-thunk,它在我的 react-native 应用程序中运行良好。我有一些“this.counterValue”,在从 api 获得响应后必须更新该值。由于 api 获取方法在另一个动作文件中实现,并且在该文件中实现响应。那么,必须如何实现才能使这项工作正常进行。我不希望“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));
            });
        }
    }
4

2 回答 2

1

使用 dispatch 将数据发送到 reducer 并在 reducer 中更新状态值,然后您可以在组件中使用它。

减速器

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[]
}

只需将其存储在 props 和 state 中,您就可以轻松操作它

于 2019-08-08T05:21:42.597 回答
0

调度你的动作后,你必须更新你的减速器

 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}
   }
于 2019-08-08T05:26:39.660 回答