【问题标题】:React-Native Not Merging Props After ComponentDidUpdate call to Async在 ComponentDidUpdate 调用 Async 之后,React-Native 不合并道具
【发布时间】:2017-04-19 05:05:04
【问题描述】:

我正在学习如何在 react-native 中设置异步 api 调用。我正在使用 axios。我正在ComponentDidMount 上发送一个正在成功更改/更新我的一般状态的调度。问题是我似乎无法使用这个“数据”。

import React, { Component, PropTypes } from 'react'
import { StyleSheet, View, Text, TouchableOpacity } from 'react-native'
import { connect } from 'react-redux'
import { getMakes} from "../actions/getPrice"
import * as PriceActions from '../actions/getPrice'


@connect((store) => {
  return {
    cars: store.cars
  };
})
export default class CounterContainer extends Component {

  constructor(props) {
    super(props);
    this.state = {
        cars: {

        }
    }
  }

  componentDidMount() {
    this.props.dispatch(getMakes())
  }


  render() {
    return (
      <View style={styles.container}>

        <TouchableOpacity>
          <Text style={styles.back}>Data: {this.props.cars.modelsCount}</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

既然动作正常,那一定是我的reducer有问题吧?如下:

function getPrice(state={
    cars: [],
    fetching: false,
    fetched: false,
    error: null,
  }, action) {
    switch (action.type) {
      case "FETCH_CARS": {
        return {...state, fetching: true}
      }
      case "FETCH_CARS_REJECTED": {
        return {...state, fetching: false, error: action.payload}
      }
      case "FETCH_CARS_FULFILLED": {
        return {
          ...state,
          fetching: false,
          fetched: true,
          cars: action.payload,
        }
      } 
    }
    return state
}

export default getPrice;

【问题讨论】:

    标签: asynchronous react-native store reducers axios


    【解决方案1】:

    mapStateToProps 将整个状态树作为第一个参数。 如果截图上的state 是你的完整redux 状态,那么connecto 应该是这样的:

    @connect((store) => {
      return {
        cars: store.priceReducer.cars
      };
    })
    

    【讨论】:

    • 哇,真不敢相信我错过了。谢谢。
    猜你喜欢
    • 2021-07-09
    • 2020-09-15
    • 1970-01-01
    • 2015-08-26
    • 2019-06-30
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多