【问题标题】:Redux React Native - Action not passing data to reducerRedux React Native - 操作未将数据传递给减速器
【发布时间】:2018-03-24 17:17:46
【问题描述】:

我是 Redux 的新手,这可能是一些愚蠢的错误。我正在尝试在 Action 中进行 Api 调用并将数据传递给减速器。我可以看到来自 api 调用的响应,但由于某种原因,它没有与 reducer 正确共享数据,或者我不知道如何将状态正确传递和呈现给 home.js。请在下面找到 action - reducers - store.js - home.js

动作文件

export const DATA_AVAILABLE = 'DATA_AVAILABLE';


export function getData(){
    return (dispatch) => {

        //Make API Call
   

        fetch("MY API URL").then((response) => {
          return response.json();
        }).then((data) => {
                    var data  = data.articles;
                    console.log(data)
                    dispatch({type: DATA_AVAILABLE, data:data});
        })
    };
}

减速器

import { combineReducers } from 'redux';

import { DATA_AVAILABLE } from "../actions/" //Import the actions types constant we defined in our actions

let dataState = {
  data: [],
  loading:true
};

const dataReducer = (state = dataState, action) => {
    switch (action.type) {
        case DATA_AVAILABLE:
            state = Object.assign({}, state, { data: action.data, loading:false });
            console.log(dataState)
            return state;
        default:
            return state;
    }
};

// Combine all the reducers
const rootReducer = combineReducers({
    dataReducer
    // ,[ANOTHER REDUCER], [ANOTHER REDUCER] ....
})

export default rootReducer;

STORE.JS

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import reducers from '../app/reducers/index'; //Import the reducer

// Connect our store to the reducers
export default createStore(reducers, applyMiddleware(thunk));

HOME.JS

'use strict';

import React, { Component } from 'react';
import {
    StyleSheet,
    FlatList,
    View,
    Text,
    ActivityIndicator
} from 'react-native';

import {bindActionCreators} from 'redux';
import { connect } from 'react-redux';

import * as Actions from '../actions'; //Import your actions

class Home extends Component {
    constructor(props) {
        super(props);

        this.state = {
        };

        this.renderItem = this.renderItem.bind(this);
    }

    componentDidMount() {
        this.props.getData(); //call our action

    }

    render() {
        if (this.props.loading) {
            return (
                <View style={styles.activityIndicatorContainer}>
                    <ActivityIndicator animating={true}/>
                </View>
            );
        } else {
          console.log(this.state)
            return (
                <View style={{flex:1, backgroundColor: '#F5F5F5', paddingTop:20}}>
                    <FlatList
                        ref='listRef'
                        data={this.props.data}
                        renderItem={this.renderItem}
                        keyExtractor={(item, index) => index}/>
                </View>
            );
        }
    }

    renderItem({item, index}) {
        return (
            <View style={styles.row}>
                <Text style={styles.title}>
                {this.props.data.title}
                </Text>
                <Text style={styles.description}>
                </Text>
            </View>
        )
    }
};



// The function takes data from the app current state,
// and insert/links it into the props of our component.
// This function makes Redux know that this component needs to be passed a piece of the state
function mapStateToProps(state, props) {
    return {
        loading: state.dataReducer.loading,
        data: state.dataReducer.date
    }
}

// Doing this merges our actions into the component’s props,
// while wrapping them in dispatch() so that they immediately dispatch an Action.
// Just by doing this, we will have access to the actions defined in out actions file (action/home.js)
function mapDispatchToProps(dispatch) {
    return bindActionCreators(Actions, dispatch);
}

//Connect everything
export default connect(mapStateToProps, mapDispatchToProps)(Home);

【问题讨论】:

  • 你在使用redux-thunk吗?
  • @Tony 是的,这是 store.js 文件 import { createStore, applyMiddleware } from 'redux';从'redux-thunk'导入thunk;从 '../app/reducers/index' 导入减速器; //导入reducer //将我们的store连接到reducers export default createStore(reducers, applyMiddleware(thunk));
  • console.log(dataState)? `
  • @RIYAJKHAN 它返回空... Object { "data": Array [], "loading": true, }
  • 是的,dataState 只是您的默认初始状态;你有 console.log(action) 在你的减速机里看看有什么东西到达了吗?

标签: javascript json reactjs react-native redux


【解决方案1】:

您并没有正确地改变状态。 Redux 只进行浅层比较以进行优化。

它唯一的检查参考。 参考需要更新。

state = Object.assign({}, state, {
      data: [
        ...state.data, //change previous state data reference
        ...action.data //update current state data reference
      ],
      loading: false
    });

【讨论】:

  • 感谢@RIYAJ KHAN。此时我想我的问题出在 home.js 中。当我在 home.js 中执行 console.log(this.props.data) 时,我只有 Object {}
  • @AlessioChiffi data: state.dataReducer.date ..它应该是你在减速器中定义的data
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 2017-08-31
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多