如何在响应中使用Redux从api获取数据

时间:2019-09-27 17:43:25

标签: reactjs api redux react-redux

您好,我刚刚开始学习redux,目前遇到了问题,我有一个API,我想从中获取信息并将其用于其他组件,如果您能帮助我,我将不胜感激

import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from "redux-thunk";
import { createLogger } from "redux-logger";
import { BrowserRouter} from "react-router-dom";
import Reducer from './Reducers';

import App from './App';
import fetchSimcards from './Actions/fetchSimcards';

const middleware = [ thunk ];
middleware.push( createLogger() );

const store = createStore(
Reducer
applyMiddleware(...middleware),
);


import * as serviceWorker from './serviceWorker';

store.dispatch(fetchSimcards());

render(
<Provider store={store}>
    <BrowserRouter>
        <App />
    </BrowserRouter>
</Provider>,

document.getElementById('root')
 );

 serviceWorker.unregister();

这是我的动作文件

import * as type from '../Constans/ActionTypes';

 export const ReceiveSimcards = Simcards => ({
type: type.RECEIVE_SIMCARDS,
Simcards
});

这是我的减速器文件

import { combineReducers } from "redux";

const Simcards = ( state = {}, action ) => {
console.log( state, action );
return state;
};

export default combineReducers({
Simcards
});

这是我的Simcard容器文件

import React, {Component} from 'react';
import SimcardList from "../Component/SimcardList";
import { connect } from "react-redux";

class SimcardContainer extends Component {
render() {
    const Simcards = this.props;
    return (
        <div>
            <SimcardList title={"Simcards"} />
            <div className="TableNumberItem">{Simcards.SimCardNumber}</div>
            <div className="TableNumberItem">{Simcards.SimCardDescription}</div>
            <div className="TableNumberItem">{Simcards.TeammatePrice}</div>
        </div>
    );
}
}

export default connect()(SimcardContainer);

我想在主页上显示此容器

1 个答案:

答案 0 :(得分:0)

使用redux,您应该调用所有API和处理逻辑代码。 动作fetchAPI的示例:

   export const fetchAPI = () = async dispatch => {
        let response = null;
        try {
            response = await axios.get('api/...')
            // Example use axios
            dispatch(fetchSuccess(response.data)) 
            // To handle in reducer with redux
        } catch (error) {
            ... Handle error here
        }
    }
    const fetchSuccess = data => ({
        type: FETCH_SUCCESS,
        data: response.data
    })

在组件中,您可以使用connect获取状态和操作:

    import { bindActionCreators } from 'redux';
    import React, { Component } from 'react';
    import SimcardList from "../Component/SimcardList";
    import { connect } from "react-redux";
    import * as _Actions from '../../action/index'

    class SimcardContainer extends Component {
        componentDidMount(){
            const { fetchAPI } = this.props.actions;
            **fetchAPI();** // Call API here
        }
        render() {
            const { stateReducer} = this.props;
            console.log(stateReducer) 
            // Here, you will see data that you handled in reducer 
            // with action type FETCH_SUCCESS
            // You should remember data that you fetch from API is asynchronous,
            // So you should check like that `data && {do any thing heree}`
            return (
                <div>
                    <SimcardList title={"Simcards"} />
                    <div className="TableNumberItem">{Simcards.SimCardNumber}</div>
                    <div className="TableNumberItem">{Simcards.SimCardDescription}</div>
                    <div className="TableNumberItem">{Simcards.TeammatePrice}</div>
                </div>
            );
        }
    }
    const mapStateToProps = state => ({
        stateReducer: state  
    })
    const mapDispatchToProps = dispatch => ({
        actions: bindActionCreators(_Actions, dispatch)
    })
    export default connect(mapStateToProps, mapDispatchToProps)(SimcardContainer)