从数据库获取数据后,本机无响应

时间:2019-05-26 13:02:27

标签: react-native fetch rerender

我有index.js个包含Tabs的标签,每个选项卡呈现相同的组件(animate.js),但具有不同的道具,其代码如下:

index.js

categoryList.map((item,index) => {
    if(item.head_category == category_id)
      return (
          <Tab heading={item.category_name} key={index}>
            <Animate category_id={item.category_id}/>
          </Tab>
        )
    });

animate.js中,我收到了category_id号,并使用redux提取了数据,数据又恢复了

对于第一个animate.js,在数据返回后没有任何反应,但是如果我切换选项卡,一切都会正常进行

animate.js

import React from 'react';
import { InteractionManager, StyleSheet, Text, View, Button } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {LineDotsLoader} from 'react-native-indicator';

import {goodsAction} from './redux/actions'

class animate extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      category_id:'',
      loading:true,
    };
    console.log('constructor');
  }
componentDidMount(){
  const { category_id, category_name } = this.props;
  this.props.goodsAction({category_id}); // My fetching Action
  console.log(`componentDidMount `);
}
componentWillReceiveProps(nextProps){
    console.log(`componentWillReceiveProps`)
}
static getDerivedStateFromProps(props, state){
  console.log(` getDerivedStateFromProps `);
  return null;
  }
componentDidUpdate(prevProps, prevState) {
    console.log(` componentDidUpdate `);
  }

  renderPage() {    
    return (
      <View style={{ flex: 1 }}>
        // anything 
      </View>
    );
  }
  render(props) {
    console.log(`render`);
if (this.props.loading) { 
// if redux still fetching return loading:true else return false
  return(<View style={styles.container}><LineDotsLoader /></View>)}
return (
        <View style={styles.container}>
          {this.renderPage()} // or anything
        </View>
    );
  }
}


const mapStateToProps = state => {
  return {
    error: state.goods.error,
    loading: state.goods.loading,
    goods: state.goods.goods
  }
}

export default connect(mapStateToProps, { goodsAction })(animate);

我的控制台映像

console log

修改

这是我的goodsRedusers.js

import {
  GOODS_LOADING_ATTEMPT,
  GOODS_REFRESH_ATTEMPT,
  GOODS_LOADED,
  GOODS_FAILED
} from '../actions/types';

const INITIAL_STATE = { goods:[], loading: true, error: '', }

export default (state = INITIAL_STATE, action) => {
  switch(action.type) {
    case GOODS_LOADING_ATTEMPT://dispatch before connecting to db
      return {...INITIAL_STATE, loading: true }
    case GOODS_FAILED:
      return {...INITIAL_STATE, loading: false, error: action.error  }
    case GOODS_LOADED://dispatch after data gets back
      return {...INITIAL_STATE, loading: false, goods: action.goods  }
    default:
      return state;
  }
}

1 个答案:

答案 0 :(得分:0)

static getDerivedStateFromProps(props, state){
  console.log(` getDerivedStateFromProps `);
  return null;
  }

如果您要更改道具,则返回null不会更新状态。 尝试删除此代码。