【问题标题】:I am using redux in react native application to fetch and display data but its not updating on data change from backend我在反应本机应用程序中使用 redux 来获取和显示数据,但它没有更新来自后端的数据更改
【发布时间】:2020-06-02 02:08:20
【问题描述】:

我在我的 React-Native 应用程序中使用 Redux。 我正在从 api 调用中获取数据,并在 ListItem 上成功渲染它。 我能够获取和显示数据,但除非我重新访问该页面,否则数据不会自动更新。 甚至值都没有存储到应用程序中 我从构造函数和 componentDidMount 方法中的操作调用方法。 你能检查一下代码并告诉我哪里出错了。

这里是 action.js

import { 
    FETCHING_PRODUCT_REQUEST, 
    FETCHING_PRODUCT_SUCCESS, 
    FETCHING_PRODUCT_FAILURE 
} from './types';

export const fetchingProductRequest = () => ({
    type : FETCHING_PRODUCT_REQUEST
});

export const fetchingProductSuccess = (json) => ({
    type : FETCHING_PRODUCT_SUCCESS,
    payload : json
});

export const fetchingProductFailure = (error) => ({
    type : FETCHING_PRODUCT_FAILURE,
    payload : error
});

export const fetchProduct = () => {
    return async dispatch => {
        dispatch(fetchingProductRequest());
        try {
            let response = await fetch("http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop");
            let json = await response.json();
            dispatch(fetchingProductSuccess(json));
        } catch(error) {
            dispatch(fetchingProductFailure(error));
        }
    }
}

我的 reducer.js

import { 
    FETCHING_PRODUCT_REQUEST, 
    FETCHING_PRODUCT_SUCCESS, 
    FETCHING_PRODUCT_FAILURE 
} from './../actions/types';

const initialState = {
    loading : false,
    errorMessage : '',
    shops: []
}

const products = ( state = initialState, action ) => {
    switch(action.type) {
        case FETCHING_PRODUCT_REQUEST :
            return { ...state, loading: true} ;
        case FETCHING_PRODUCT_SUCCESS : 
            return { ...this.state, loading: false, shops: action.payload };
        case FETCHING_PRODUCT_FAILURE : 
            return { ...state, loading: false, errorMessage: action.payload};
    }
};

export default products;

product.js

import * as React from 'react';

import { FlatList , ActivityIndicator} from 'react-native';

import { ListItem } from 'react-native-elements';

import { fetchProduct } from './../../actions/products';

import { connect } from 'react-redux';

import propTypes from 'prop-types';

class Product extends React.Component {

  constructor(props) {
    super(props);
    this.props.fetchProduct();
    this.state = {
      loading : true,
      shops : '',
     isFetching: false,
     active : true,
    }
   }


   fetchProducts() {
    const shopid = 13;
    fetch(`http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop`)
        .then(response => response.json())
          .then((responseJson)=> {
              this.setState({
                 loading: false,
                 shops: responseJson
              })
             alert(JSON.stringify(this.state.shops));
        })
    .catch(error=>console.log(error)) //to catch the errors if any
   }

    componentDidMount(){
      // this.fetchProducts();
      this.props.fetchProduct().then(this.setState({loading : false}));
    }



  renderItem = ({ item }) => (
  <ListItem
    title={item.name}
    subtitle={item.name}
    leftAvatar={{
      source: item.avatar && { uri: item.avatar },
      title: item.name[0]
    }}
    bottomDivider
    chevron
  />
)

render () {
    if(!this.state.loading)
    { 
      if(this.props.shopsInfo.loading)
      {
        return (
        <ActivityIndicator/>
        )
      }
      else
      {
        return (
        <FlatList
                vertical
                showsVerticalScrollIndicator={false}
                data={this.props.shopsInfo.shops}
                renderItem={this.renderItem}
              />
      )
      }
    }
    else
    {
      return (
        <ActivityIndicator/>
        )
    }
  }
}

Product.propTypes = {
  fetchProduct:  propTypes.func.isRequired
};


const mapStateToProps = (state) => {
  return { shopsInfo: state };
}

function mapDispatchToProps (dispatch) {
  return {
    fetchProduct: () => dispatch(fetchProduct())
  }
} 

export default connect(mapStateToProps, mapDispatchToProps)(Product);

【问题讨论】:

  • 从后端更新数据不会反映在应用程序中,需要定期检查才能实现,您可以通过参考 react native 的生命周期来定制一些方法来获得更好的用户体验

标签: react-native redux react-redux redux-thunk reducers


【解决方案1】:

问题是您在 mapStateToProps 函数中传递了错误的道具。 在减速器中,您更新商店道具中的响应值。 为了获取更新后的值,您需要通过 shop 属性来获取值。

const mapStateToProps = (state) => { 
   const { shops: state };  
   return {shops};
} 

【讨论】:

  • const mapStateToProps = (state) => { return { storesInfo: state };这里的 shopInfo 就像一个变量,用来存储 props 中的所有状态。
  • 如果您通过了完整状态,然后使用控制台检查mapStateToProps 和组件,您的更新数据是否返回这里。如果您没有收到数据,只需检查您的配置存储,它是否正确更新了减速器。
【解决方案2】:

1.不更新来自后端的数据更改。

您必须定期调用 api 来获取更新的数据。 Redux 实现并不意味着它会在有任何变化时从服务器获取数据。

2。甚至值也不会存储到应用中

如果你期望 redux 会存储数据,即使你会关闭/杀死一个应用程序,它也不会。您拥有持久化数据以便使用它或将其存储在缓存中。看看redux-persist

【讨论】:

  • 哦,好的,我明白了。对我来说,更新数据变化很重要。你能为我提供任何快速指南吗?
  • 嗯,据我所知没有直接的方法来实现它。您可以做的只是定期检查数据更改,或者可能是套接字编程,它可以在数据更改时通知您。如果不是大产品,我不会推荐socket。
  • 好的.. 我将使用定期间隔来更新操作中的状态。谢谢你。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2018-02-08
  • 2020-03-05
  • 1970-01-01
相关资源
最近更新 更多