使用Redux

时间:2018-08-24 21:10:34

标签: javascript reactjs redux socket.io redux-thunk

我正在接收数据,但是问题是我只能在同一文件 api.js 中访问它。如我所知,它没有返回任何值。我做了很多代码片段的变体。它返回initial stateundefined。有趣的是,如果存在error,它将填充error对象。抱歉,这么多代码,但是有人可以帮我成功地用socket.io实现React/ Redux.

这是我到目前为止得到的:

api.js
在这里,我已成功连接到API,接收了数据,但无法在此文件之外使用它。如果返回一个对象,它将是undefined,但是如果我console.log甚至是return一个console.log并在其他组件/文件中使用该文件,则数据将显示在我的控制台,但只有那样,而且只能在我的控制台中……无法调度数据,并且无法在我要构建的应用程序中重复使用它们。


import axios from 'axios';
import io from "socket.io-client";

export function fetchData() {

const configUrl = 'API endpoint';
    axios.get(configUrl).then(res => {        
         const socketUrl = res.data.config.liveDistributionSSL;      
            const  socket = io(socketUrl); 

            socket.on('connect', function () {            
                socket.emit('subscribe', {                 
                        subscribeMode: 'topSportBets',                 
                        language: {                    
                             default: 'en'                 
                           },
                       deliveryPlatform: 'WebSubscribe',
                       playerUuid: null,                 
                       subscribeOptions: {                     
                       autoSubscribe: true,                     
                       betCount: 3,      
                       excludeMeta: false,                     
                       resubscriptions: 0,                     
                       fullBetMeta: true,                    
                       browser: {}
                       }           
                   });


                    let relevantData = {}; // Object that I'm trying to assign values to and return


                socket.on('message', async (message) => {

                  switch (message.type) {      

                      case 'state':    // We have all the data needed to show
                        relevantData = await Object.values(Object.values(message.data)[9]);
                        break;

                        case 'currentMatches':
                        // We have matches to update
                        console.log('Matches =>', message.contentEncoding);
                        break;

                        case 'betchange':
                        // We have match bets to update
                        console.log('Match bets =>', message.contentEncoding);
                        break;

                        default: break;
                      }   
                      return relevantData;      
                   });
                   socket.on("disconnect", () => console.log("Client disconnected"));
               });
          });

        }

actions / index.js
这是我的主要动作创作者。您看到的代码是我最后一次尝试新方法的尝试,结果仍然相同。


import { GET_DATA, GET_ERROR } from './types';
import { fetchData } from '../api'

export const getDataAsync = () => async dispatch => {
    try {
        const response = await fetchData();
            dispatch({ type: GET_DATA, payload: response });
    } catch (e) {
            dispatch({ type: GET_ERROR, payload: 'Something went wrong ', e });
        }
    };

reducers / data_reducer.js
在这里,我正在制作一个简单的减速器,并根据payload更改initial state

import { GET_DATA, GET_ERROR } from '../actions/types';

const INITIAL_STATE = {
  apiData: {},
  errorMessage: {}
};

const dataReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case GET_DATA:
            return { ...state, apiData: action.payload };

        case GET_ERROR:
            return { ...state, errorMessage: action.payload };

        default:
            return state;
    }
}

export default dataReducer;

reducers / root_reducer.js
这里我将归约化器,稍后将我的root_reducer实现为我的store配置

import { combineReducers } from 'redux';
import dataReducer from './data_reducer';

const rootReducer = combineReducers({
    allData: dataReducer
});

export default rootReducer;

PrimaryLayoutContainer.js
*这将是我的主要layout容器,其中我正在实现路由,显示PrimaryLayout组件,而其中**我正试图传递值ass props *

import React, { Component } from 'react';
import {connect} from 'react-redux';
import PrimaryLayout from "../components/PrimaryLayout";
import { withRouter } from 'react-router'
import * as myData from '../actions';


class PrimaryLayoutContainerComponent extends Component {
    render() {
        return (
            <div>
                <PrimaryLayout history={this.props.history}
                               allData={this.props.allData}
                />
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        allData: state.allData
    }
}

export default withRouter(connect(mapStateToProps, myData)(PrimaryLayoutContainerComponent));

PrimaryLayout.js
我要在其中实现数据,所有路由并显示主要组件等,但是在这里我停了下来,因为我没有得到所需的数据

import React, {Component} from 'react';
import {Switch, Route, Redirect, Link} from 'react-router-dom';
import Favorites from './Favorites';
... a lot of other imports of my components


class PrimaryLayout extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentRoute: '',
            // data: {}
        }
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            currentRoute: nextProps.history.location.pathname
        })
    }

    componentWillMount() {
        this.setState({
            currentRoute: this.props.history.location.pathname
        })
    }

    componentDidMount() {
        console.log(this.props); // Where i'm trying to get access to the data
    }

    render() {

        const {currentRoute} = this.state;

        return (

            <div className='main-nav'>
            <nav className="topnav">
            <ul>
                <li className={currentRoute === "/favorites" ? "active" : ""}>
                    <Link to="/favorites"><div className='star'></div> Favorites </Link> </li>

                <li className={currentRoute === "/football" ? "active" : ""}>
                    <Link to="/football"><div className='football'></div> Football </Link> </li>

                <li className={currentRoute === "/basketball" ? "active" : ""}>
                    <Link to="/basketball"><div className='basketball'></div> Basketball </Link> </li>

                <li className={currentRoute === "/tennis" ? "active" : ""}>
                    <Link to="/tennis"><div className='tennis'></div> Tennis </Link> </li>

                <li className={currentRoute === "/baseball" ? "active" : ""}>
                    <Link to="/baseball"><div className='baseball'></div> Baseball </Link> </li>

                <li className={currentRoute === "/waterpolo" ? "active" : ""}>
                    <Link to="/waterpolo"><div className='waterpolo'></div> Waterpolo </Link> </li>

            </ul>
          </nav>

                <main>
                    <Switch>
                        <Route path='/favorites' component={Favorites} />
                        <Route path='/football' component={Football} />
                        <Route path='/basketball' component={Basketball} />
                        <Route path='/tennis' component={Tennis} />
                        <Route path='/baseball' component={Baseball} />
                        <Route path='/waterpolo' component={Waterpolo} />
                        <Route path='/volleyball' component={Volleyball} />
                        <Route path='/handball' component={Handball} />
                        <Route path='/formula1' component={Formula} />
                        <Redirect to="/football"/>
                    </Switch>
                </main>

            </div>
        )
    }
}


export default PrimaryLayout;

index.js
这将是我的主要index.js文件,我将在其中配置存储和将元素渲染到DOM

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import './assets/styles/App.css';

import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers/root_reducer';
import thunk from 'redux-thunk';

function configureStore() {
  return createStore(
    rootReducer,
    applyMiddleware(thunk)
  );
}

const myStore = configureStore();

ReactDOM.render(
  <Provider store={myStore}>
   <App />
  </Provider>,
   document.getElementById('root')
 )

注意:


就像我之前说过的那样,我已成功连接到API端点,并接收了必要的数据,但是我只能在同一文件api.js中对其进行操作。我一整天都在Google上工作,但没有发现与我的问题有关的任何信息。 PHP,Java有很多示例,但React,Redux等没有很多示例...我以前从未使用过Socket.io,所以请亲爱的朋友们帮帮我...:/

这里的主要问题是: 我如何成功实现Scoket.io并使用Redux分发API数据,丢弃所有主要的React组件,而不是非常 DRY ,意味着在每个组件和每个组件中实现相同的逻辑是时候获取所有数据,而不仅仅是相关数据了。

如果我可以在一个地方(在api.js文件之外)进行此操作,那么我可以在任何地方进行此操作,该答复将不胜感激,并且将被立即接受。

1 个答案:

答案 0 :(得分:0)

我更改了 api.js 文件。 async - await导致了问题,加上return语句在错误的位置。新秀错误。

import axios from 'axios';
import io from "socket.io-client";

export const fetchData = () => {

let apiData = {}; // Object that I'm trying to assign values to and return
apiData.bets = [];
apiData.matches = [];

const configUrl = 'API URI';
axios.get(configUrl).then(res => {        
        const socketUrl = res.data.config.liveDistributionSSL;      
        const  socket = io(socketUrl); 
        socket.on('connect', function () {            
            socket.emit('subscribe', {                 
                    subscribeMode: 'topSportBets',                 
                    language: {                    
                         default: 'en'                 
                       },
                   deliveryPlatform: 'WebSubscribe',
                   playerUuid: null,                 
                   subscribeOptions: {                     
                   autoSubscribe: true,                     
                   betCount: 3,      
                   excludeMeta: false,                     
                   resubscriptions: 0,                     
                   fullBetMeta: true,                    
                   browser: {}
                   }           
               });

            socket.on('message', (message) => {

              switch (message.type) {      

                case 'state':    // We have all the data needed to show
                apiData.bets = Object.assign(message.data.bets);
                apiData.matches = Object.assign(message.data.matches);
                break;

                // ... etc ...

                default: break;
                  }
               });
               socket.on("disconnect", () => console.log("Client disconnected"));
           });
      });
      return apiData;
    }

之后,我实现了更好的store配置。实际上,我为它制作了一个外部文件,确切地说是三个文件,具体取决于开发进度(dev,stage,prod)。这是 configureStore.dev.js 文件:

import thunk from 'redux-thunk';
import {
    createStore,
    applyMiddleware,
    compose
} from 'redux';
import rootReducer from '../reducers/root_reducer';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';

export default function configureStore(initialState) {
    return createStore(
        rootReducer,
        compose(
            applyMiddleware(thunk, reduxImmutableStateInvariant()),
            window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
        )
    );
}

最后我做了所有工作,我将 PrimaryLayoutContainerComponent.js 更改为如下所示。通过所有这些简单但重要的更改,我可以访问所有相关数据,因为这些数据在整个应用程序中都是实时更新的。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PrimaryLayout from "../components/PrimaryLayout";
import { withRouter } from 'react-router'
import * as myData from '../actions';


// Since this is our Primary Layout Container here we in addition to mapping state to props also
// are dispatching our props and binding our action creators, also using 'withRouter' HOC
// to get access to the history object’s properties and make it easy to navigate through our app.

class PrimaryLayoutContainerComponent extends Component {
    render() {
        return (
            <div>
                <PrimaryLayout history={this.props.history}
                               allData={this.props.allData}
                               getDataAsync={this.props.actions.getDataAsync}
                />
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {allData: state.allData.apiData}
}

const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators({...myData}, dispatch)
    };
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(PrimaryLayoutContainerComponent));

一个小注释:我总是回答自己的问题,而不仅仅是用n删除它们,而是我自己找到解决方案。我这样做的原因很简单,那就是将来可能会对某人有所帮助。