【问题标题】:Redux fetch data from apiRedux 从 api 获取数据
【发布时间】:2016-10-19 10:33:59
【问题描述】:

我正在尝试使用 Redux 从 api 获取一些数据。我的代码如下所示:

行动:

// Import libraries
import axios from 'axios';

// Import types
import {
  GET_ALL_PICKS
} from './types';

export const getAllPicks = ({ token }) => {
  const getPicks = (dispatch) => {
    axios({
      method: 'get',
      url: 'http://myapi/',
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    .then((response) => {
      console.log(response.data); // First log here returns data just fine
      dispatch({
        type: GET_ALL_PICKS,
        payload: response.data
      });
    })
    .catch((error) => {
      console.log(error);
    });
  };

  return getPicks;
};

减速机:

// Import types
import {
  GET_ALL_PICKS
} from '../actions/types';

// Set Initial State
const INITIAL_STATE = {
  allPicks: {},
  loading: false,
  error: ''
};

// Make pick reducers
export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case GET_ALL_PICKS:
      return { ...state, allPicks: action.payload }; // Logging action.payload here returns data just fine
    default:
      return state;
  }
};

组件:

// Import Libraries
import React, { Component } from 'react';
import { Text } from 'react-native';
import { connect } from 'react-redux';
import {
  getAllPicks
} from '../actions/picks';

// Make Component
class HomeScreen extends Component {
  // Fetch Data
  componentWillMount() {
    const { token } = this.props;

    this.props.getAllPicks({ token });
  }

  // Test response
  componentDidMount() {
    console.log(this.props.allPicks); // This log returns empty object, why?!
  }

  render() {
    return (
      <Text>Test</Text>
    );
  }
}

const mapStateToProps = ({ auth, picks }) => {
  const { token } = auth;
  const { allPicks } = picks;

  return {
    token,
    allPicks
  };
};

export default connect(mapStateToProps, { getAllPicks })(HomeScreen);

当我运行应用程序时,我会在操作 console.log 中看到数据,如果我在减速器中运行 console.log(action.payload),我会看到数据很好,但在组件中我看到一个空数组,这表明我没有挂钩我的减速器中的数据是否正确?这是日志的屏幕截图:

在谷歌搜索后,我也在减速器中尝试过这个:

  return Object.assign({}, state, {
    allPicks: action.payload
  });

但我又得到了同样的结果。谁能向我解释我做错了什么?

【问题讨论】:

    标签: react-native redux react-redux


    【解决方案1】:

    您混淆了组件生命周期和 API 生命周期。

    在实践中,正在发生的事情是:

    • 组件WillMount
    • getAllPicks
    • componentDidMount(此时 API 未返回,选择为空)
    • [...等待 API 返回]
    • 然后 API 将返回数据,但为时已晚

    然后您需要做的是在render() 函数中检查您的“选择”状态,由于connect() 函数,每次您的状态更改时都会更新该状态(当API 返回时发生)。

    您还可以使用componentWillUpdate 来检查选择是否正确更新,而不是componentDidMount,这与正在更新的道具无关。

    【讨论】:

      猜你喜欢
      • 2021-09-27
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2019-03-15
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      相关资源
      最近更新 更多