Redux:不称为Reducer

时间:2018-01-21 07:10:52

标签: reactjs react-native react-redux

我正在制作React Native和Redux的移动应用程序。

似乎我的行为,状态正常,因为我做了console.log他们。

这里的问题是我的减速器没有被调用。

我确实在控制台上记录了它,但没有结果。

我不知道造成这种情况的原因。

我尝试在Market.js中获取API数据

如果有人帮助我,我真的很感激。

我的github回购:https://github.com/sj602/invescoin

代码如下:

App.js

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { Stacks } from './utils/Navigation';
import {
  StyleSheet, Text, View,
} from 'react-native';
import { store } from './store';

export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Stacks />
      </Provider>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

store.js

import {
  createStore,
  applyMiddleware,
  compose
} from 'redux';
import promise from 'redux-promise';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import reducer from '../reducers';

// const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export const store = createStore(
  reducer,
  // composeEnhancers(
    applyMiddleware(thunk)
  // )
);

reducer.js

import { combineReducers } from 'redux';
import {
  GET_MARKET_CAP,
  GET_MARKET_CAP_SUCCESS,
  GET_MARKET_CAP_FAIL,
  GET_GLOBAL_INFO,
} from '../actions';


const initialState = {
  isFetching: null,
  data: '',
  hasError: false,
  errorMessage: null,
}

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case GET_MARKET_CAP:
      console.log(2)
      return ;
    case GET_MARKET_CAP_SUCCESS:
      console.log('success')
    case GET_MARKET_CAP_FAIL:
      return {
        ...state,
        marketCap: action.err
      }
    case GET_GLOBAL_INFO:
      console.log('action')
      return {
        ...state,
        bitcoinPercentage: action.bitcoinPercentage
      }
    default:
      return state;
  }
}

actions.js

 import {
  GET_MARKET_CAP,
  GET_MARKET_CAP_SUCCESS,
  GET_MARKET_CAP_FAIL,
  GET_GLOBAL_INFO
} from './types.js';
import * as api from '../utils/api';

export const getMarketCap = (coin, currency) => dispatch => {
    return api.getMarketCap(coin, currency)
        .then(data => {
          dispatch({type: GET_MARKET_CAP_SUCCESS, data})
        })
        .catch(err => {
          dispatch({type: GET_MARKET_CAP_FAIL, err})
        })
}

export function getGlobalInfo() {
    return dispatch => {
      return api.getGlobalInfo().then(data => {
          dispatch({type: GET_GLOBAL_INFO, data})
        })
  }
}

types.js

export const GET_MARKET_CAP = 'GET_MARKET_CAP';
export const GET_MARKET_CAP_SUCCESS = 'GET_MARKET_CAP_SUCCESS';
export const GET_MARKET_CAP_FAIL = 'GET_MARKET_CAP_FAIL';
export const GET_GLOBAL_INFO = 'GET_GLOBAL_INFO';
export const GET_COIN_PRICE = 'GET_COIN_PRICE';

Market.js

import React, { Component } from 'react';
import {
  View, Text, TouchableOpacity,
  ScrollView, TextInput
} from 'react-native';
import { connect } from 'react-redux';
import {
  getMarketCap,
  getGlobalInfo,
} from '../actions/index';
import * as api from '../utils/api';
import { cryptoList } from '../utils/cryptoList';

class Market extends Component {
  componentDidMount() {
    this.props.getMarketCap('bitcoin', 'KRW').then(data => data[0]['market_cap_krw'])
;
    this.props.getGlobalInfo();
  }

  render() {
    return (
      <View>
        <Text>
          {this.props.market}
        </Text>
        <Text>
          {this.props.bitcoinPercentage}
        </Text>
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    market: state.market,
    bitcoinPercentage: state.bitcoinPercentage
  }
}

export default connect(mapStateToProps, {
  getMarketCap,
  getGlobalInfo
})(Market)

api.js

const Coinmarketcap_URL = `https://api.coinmarketcap.com/v1/`;

const headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authentication': 'c23R30cm2jOOExyAsG6pf5Xxy4QwpndxaIMRs6aOZxIQoUlMVOv1tCQZL3jZz'
};

export const getMarketCap = (coin, currency) => {
  return fetch(
    `${Coinmarketcap_URL}ticker/${coin}/?convert=${currency}`,
    {
      method: 'GET',
      headers,
    }
  )
  .then(res => res.json())
  .catch(e => console.log('Error occurred : ', e))
}

export const getGlobalInfo = () => {
  return fetch(
    `${Coinmarketcap_URL}global/`,
    {
      method: 'GET',
      headers,
    }
  )
  .then(res => res.json())
  .catch(e => console.log('Error occurred : ', e))
}

3 个答案:

答案 0 :(得分:1)

我认为问题出在reducer.js L7

import { combineReducers } from 'redux';
import {
  GET_MARKET_CAP,
  GET_MARKET_CAP_SUCCESS,
  GET_MARKET_CAP_FAIL,
  GET_GLOBAL_INFO,
} from '../actions';  // <--- ../actions/index.js doesn't export these. 

../actions导入时,预计导出位于该文件夹中的index.js文件中。用于描述问题的文件名与存储库中的实际文件名不匹配。

相反,请尝试import { ... } from ../actions/types,因为types.js是实际导出这些const的文件。

希望有所帮助!

答案 1 :(得分:0)

我认为问题出在market.js文件中

import { bindActionCreators } from "redux"

function mapDispatchToProps(dipatch) {
return bindActionCreators({
  getMarketCap,
  getGlobalInfo
}, dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(Market)

现在它应该可以工作,你错过了使用dispatch绑定你的功能

答案 2 :(得分:0)

很抱歉,但我无法帮助,但我们注意到这是你的store.js还没有针对Reducer的初始状态。在create store方法的react文档中:

createStore(reducer, [preloadedState], [enhancer])

你能做一个初始状态,看看是否有效。所以你的代码看起来可能与此类似;

import {
  createStore,
  applyMiddleware,
  compose
} from 'redux';
import promise from 'redux-promise';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import reducer from '../reducers';


initialState = {Initial State of Reducers}
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export const store = createStore(
  reducer,
  intialState,
  composeEnhancers(
    applyMiddleware(thunk)
  )
);