Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

Api call happens only the first time in react-native redux

I am new to using react native redux and I am facing an issue that the api call is made only once, what if i click on another button which should render a different response based on the params and display it on the component which is a flatlist in my case. Please have a look at my code.

RecordListAction:

    import { FETCH_RECORD_LIST, FETCH_RECORD_SUCCESS, FETCH_RECORD_FAILURE } from './types.js'
    export const fetchRecordList = () => ({
    type: FETCH_RECORD_LIST
    })
    export const fetchRecordSuccess = json => ({
    type: FETCH_RECORD_SUCCESS,
    payload: json
    })
    export const fetchRecordFailure = error => ({
    type: FETCH_RECORD_FAILURE,
    payload: error
    })
    export const fetchRecordListApi = () => {
    console.log("Now I'm here!")
    return async dispatch => {
        dispatch(fetchRecordList());
        let response = await 
    fetch(url, {
            method: 'POST',
            headers: {
                'tenantid': '1',
                'Content-Type': 'application/json',
                'language': '1',
                'userid': '11'
            },
            body: JSON.stringify(global.recordListBody)
        }).then((response) => response.json())
            .then((responseJson) => {
                console.log("RecordList Action Value" + responseJson)
                dispatch(fetchRecordSuccess(responseJson.records));

            }).catch(error => {
                dispatch(fetchRecordFailure(error))
            }) }}

recordListReducer.js:

    import {FETCH_RECORD_REQUEST,FETCH_RECORD_SUCCESS,FETCH_RECORD_FAILURE} 
    from "../actions/types"

    const initialState = {
    isFetching: false,
    errorMessage : '',
    record :[]
    };
    const recordListReducer = (state = initialState,action) => {
    switch(action.type){
        case FETCH_RECORD_REQUEST:
            return { ...state, isFetching: true }
        case FETCH_RECORD_FAILURE:
            return { ...state, isFetching: false, errorMessage: action.payload };
        case FETCH_RECORD_SUCCESS:
            return{...state, isFetching:false, record:action.payload}
        default:
            return state

            }};

           
       export default recordListReducer;


  RecordListContainer.js

    import React, { Component } from 'react'
import { Text, View, StyleSheet, ActivityIndicator, Button } from 'react-native'
import PropTypes from 'prop-types';
import {fetchRecordListApi} from "../redux/actions/recordListAction"
import {connect} from "react-redux";
import DetailsViewMode from '../Enums/DetailsViewMode'
import RecordList from '../Components/RecordListComponents/RecordList';
import { Icon, Divider } from 'react-native-elements';



class RecordListContainer extends Component {
    constructor(props) {
        super(props);   
      
    }
    componentDidMount(){
    this.props.dispatch(fetchRecordListApi());
    }
    render(){
    let content = <RecordList record = {this.props.recordList.record}/>
    if(this.props.recordList.isFetching){
        content= <ActivityIndicator size="large" />
    }
    }}
    RecordListContainer.propTypes = {
    fetchRecordListApi : PropTypes.func.isRequired,
    recordList : PropTypes.object.isRequired}
    const mapStateToProps = state =>{
     return{
         recordList: state.posts
     };
     }
     export default connect(mapStateToProps)(RecordListContainer);


rootReducer.js :

    import recordListReducer from './recordListReducers';'
    import { combineReducers }  from 'redux';
    const rootReducer = combineReducers({
    posts : recordListReducer,
   });
   export default rootReducer;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could make recordListBody part of redux state or react context. Or you could make recordListBody observable and respond to changes. Here is an example of making recordListBody observable:

//object combined with global.recordListBody to add listeners
//  and notify them of changes
const recordListBodyObserver = ((observers) => {
  const removeObserver = (observer) => () => {
    observers = observers.filter((o) => o !== observer);
  };
  return {
    notify: (value) =>
      observers.forEach((observer) => observer(value)),
    add: (observer) => {
      observers.push(observer);
      return removeObserver(observer);
    },
  };
})([]);
let recordListBodyValue;
//your global object with recordListBody that will notify
//  listeners if a value for recordListBody is set
const global = {
  set recordListBody(value) {
    //notify all listeners;
    recordListBodyObserver.notify(value);
    //set the new value
    return (recordListBodyValue = value);
  },
  get recordListBody() {
    return recordListBodyValue;
  },
};
//function to create increasing id
const id = ((id) => () => id++)(1);
class App extends React.PureComponent {
  componentDidMount() {
    this.removeListener = recordListBodyObserver.add(
      (value) => {
        //you can dispatch your action here using value
        //  do not use global.recordListBody here becasue
        //  that has the old valuee
        console.log(
          'recordListBody changed from:',
          global.recordListBody,
          'to value:',
          value
        );
      }
    );
  }
  componentWillUnmount() {
    //clean up listener when component unmounts
    this.removeListener();
  }
  render() {
    return (
      <button
        onClick={() => (global.recordListBody = id())}
      >
        Change recordListBody
      </button>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...