【问题标题】:Api call happens only the first time in react-native reduxApi 调用仅在 react-native redux 中第一次发生
【发布时间】:2021-01-08 18:50:14
【问题描述】:

我是使用 react native redux 的新手,我面临一个问题,即 api 调用只进行一次,如果我单击另一个按钮,该按钮应该根据参数呈现不同的响应并将其显示在组件上在我的情况下是一个平面列表。请看我的代码。

记录列表操作:

    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;

【问题讨论】:

  • 你的意思是 fetchRecordListApi 会获取不同的东西?我不明白如何,因为无论您调用多少次它都完全相同,因为它不带任何参数。如果您的问题中的代码没有反映您的问题,并且有一个 props 发送来获取,那么请查看here,您还需要在 componentDidUpdate 上做一些事情,或者更好;忘记类并改用效果挂钩。
  • 是的,我的意思是 fetchRecordListapi 每次都会获取不同的列表,因为每个操作的主体都会不同。正文是动态的,但它不调用 api。我到底应该在 ComponentDidUpdate() 中写什么?
  • 所以如果 global.recordListBody 发生变化,你想再次获取并调度 fetchRecordSuccess 吗?
  • 是的,因为结果会不一样

标签: react-native redux react-redux


【解决方案1】:

您可以让 recordListBody 成为 redux 状态或反应上下文的一部分。或者您可以使 recordListBody 可观察并响应更改。下面是一个让 recordListBody 可观察的例子:

//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>

【讨论】:

    【解决方案2】:

    我正在使用 componentDidUpdate 并检查 props 值是否更改,当传入 props 的 body 更改时再次调用 api。

    【讨论】:

      猜你喜欢
      • 2018-12-30
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      • 2019-07-15
      • 2020-01-29
      • 1970-01-01
      相关资源
      最近更新 更多