Ответы пользователя по тегу React
  • Как правильно подключить centrifugo в React-Redux?

    @Miki8887 Автор вопроса
    Front-end разработчик
    Проблему решила. Извинюсь, что оперативно не разместила решение.
    в main.js добавляются следующие строки:
    import {Centrif} from './myCentrifugoClass.js'
    
    ReactDOM.render(
        <Provider store={store}>
            <Router history={history}>
                <Switch>
                    <Centrif>
                    <Route path='/about' component={SPageController} />
                    <Route path='/login' component={FormAuthController} />
                    <Route path='/' component={requireAuthentication(basicLayoutController)} />
                    </Centrif>
                </Switch>
            </Router>
        </Provider>,
      document.getElementById('content')
    )


    В файл reducers/actions.js:
    require ('/js/json3.min.js')
    import Centrifuge,{publish} from 'centrifuge'
    var host = window.location.origin;
    var timestamp = parseInt(new Date().getTime()/1000).toString();
    var hmacBody = timestamp;
    var secret = "ключ";
    var shaObj = new jsSHA("SHA-256", "TEXT");
    shaObj.setHMACKey(secret, "TEXT");
    shaObj.update({"input":"hello"});
    var token = shaObj.getHMAC("HEX");
    import {subscription_namemod,centrifuge} from '/src/myCentrifugoClass.js'
    //ну и уже в нужной вам функции добавляете к примеру
    subscription_path.publish(data);


    файл myCentrifugoClass.js:
    import React from 'react'
    import { connect } from 'react-redux'   // связывает хранилище Redux с компонентами React
    import { bindActionCreators } from 'redux'
    import { checkAuth,isAuthenticated,EAction,changePath,notAuthenticated } from './reducers/actions'
    import { Redirect } from 'react-router-dom'
    require ('/js/json3.min.js')
    import Centrifuge from 'centrifuge'
    var host = window.location.origin;
    var timestamp = parseInt(new Date().getTime()/1000).toString();
    var hmacBody = timestamp;
    var secret = "пишем здесь ключ";
    var shaObj = new jsSHA("SHA-256", "TEXT");
    shaObj.setHMACKey(secret, "TEXT");
    shaObj.update(hmacBody);
    var token = shaObj.getHMAC("HEX");
    var centrifuge = new Centrifuge({
        url: 'адрес где крутится центрифуга',
        user: "",
        timestamp: timestamp,
        token: token
    });
    var path; 
    export var subscriptionb;
    export var subscription_path;
    
    class Appet extends React.Component {
    
        componentWillMount(){
            var df = this;
    
            if (path==null){
                path="/"
            }
    
            centrifuge.on('connect', function() {
                console.log('Центрифуга подключена');
    
                subscription_path = centrifuge.subscribe(path, function(message) {
                        console.log('message',message.data.action);
                    switch (message.data.action){
                        case "isLogin":
                            df.props.isAuthenticated();
                        break;
                        case "isLogout":
                            df.props.notAuthenticated();
                            <Redirect to='/login'/>
                        break;
                    }
                });
    
                subscriptionb = centrifuge.subscribe('work', function(message) {
                    console.log('работает');
                });
            });
            centrifuge.connect();
        }
    
        componentDidUpdate(){
            path=this.props.location.pathname;
            console.log('Канал', path)
        }
    
        render() {
            return (
                <div>
                    {this.props.children}
                </div>
            )
        }
    }
    
    export const Centrif = connect(state => ({state : state}),
                dispatch => bindActionCreators({isAuthenticated,changePath,notAuthenticated}, dispatch))(Appet)
    Ответ написан
    Комментировать
  • Почему не работают вложенные маршруты внутри дочерних компонентов ( React-router 4, Redux)?

    @Miki8887 Автор вопроса
    Front-end разработчик
    А решение совсем простое...нужно в родительском и дочернем компоненте обернуть connect в withRouter (https://reacttraining.com/react-router/core/guides...
    Как я могла только забыть про это...
    Ответ написан
    3 комментария