首页 > 解决方案 > React Native FlatList 没有渲染 Axios API 请求

问题描述

我是本机反应的新手,我在处理道具和状态时遇到了问题,当我使用 redux 时,我得到了以正确的形式呈现平面列表所需的数据,但只有平面列表中的数据属性如何将 {this.props.customers} 视为未定义。这是我的代码:

  componentWillMount() {
    debugger;
    this.props.getCustomers();
    debugger;
  }

  componentDidUpdate(prevProps) {
    if (prevProps.customers !== this.props.customers) {
      this.props.getCustomers();
    }
  }


  render = () => {
    return (
      <View>
        <FlatList
          data={this.props.customers}
          renderItem={({ item }) =>
            <View style={styles.GridViewContainer}>
              <Text style={styles.GridViewTextLayout}>{item.name}</Text>
            </View>}
          keyExtractor={(x, index) => index}
          numColumns={3}
        />
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  const customers = state.customers;
  console.log(customers);
  debugger
  return customers;

};


export default connect(mapStateToProps, {
  getCustomers
})(CustomersList);

和 getCustomers 行动:

export const getCustomers = () => {
    debugger;
    return (dispatch) => {
        dispatch(setCustomerLoading)
        axios
            .get('https://calm-sands-26165.herokuapp.com/api/customers')
            .then(res =>
                dispatch({
                    type: GET_CUSTOMERS,
                    payload: res.data,
                })
            )
            .catch(err =>
                dispatch({
                    type: GET_ERRORS,
                    payload: null
                })
            );
    };
}

提前谢谢。

标签: androidreact-nativereduxredux-thunkreact-native-flatlist

解决方案


在 mapStateToProps 中,您应该返回一个对象,而不是一个值。该对象中的每个条目都将是连接到商店的组件的道具。

在您的情况下,这应该是解决方法:

const mapStateToProps = (state) => {
  const customers = state.customers;
  return { customers };
};


推荐阅读