N
N
nastyskafomka2019-04-27 14:52:08
JavaScript
nastyskafomka, 2019-04-27 14:52:08

Why are React scripts executed immediately?

Hello, I am making a vk app and I have a problem: I have the
following code in Home.js:

import React from 'react';
import $ from "jquery";
import {Panel, ListItem, Button, Group, Div, Avatar, PanelHeader} from '@vkontakte/vkui';
import "./sa.css";
import connect from '@vkontakte/vkui-connect';
import {rules,tt,mess} from "../what";

    // connect.send("VKWebAppInit", {});
    connect.send("VKWebAppGetAuthToken", {"app_id": 6962654, "scope": "friends"});

const Home = ({id, go, fetchedUser, ff}) => (
    <Panel id={id}>
        <PanelHeader>Главная</PanelHeader>
        {fetchedUser &&
        <Group title={`Здравствуйте, ${fetchedUser.first_name}`}>
            <ListItem
                before={fetchedUser.photo_200 ? <Avatar src={fetchedUser.photo_200}/> : null}
                description={fetchedUser.city && fetchedUser.city.title ? fetchedUser.city.title : ''}
            >
                {`${fetchedUser.first_name} ${fetchedUser.last_name}`}
            </ListItem>
        </Group>}
        <Group>
            <ListItem>
                <div className="message">
                    <p>text</p>
                </div>
            </ListItem>
        </Group>
        <Group>
            <ListItem>
                s
            </ListItem>
            <ListItem id="skdsmdksd">
                <p id="skdsmdksd">sd</p>
            </ListItem>
        </Group>

        <Group title="Быстрая навигация">
            <Div>
                <Button className="def_btn" size="xl" level="2" onClick={go} data-to="persik">
                    Связаться с менеджером
                </Button>

                <Button className="def_btn" size="xl" level="2" onClick={go} data-to="test">
                    Выбрать паблики
                </Button>
                <Button className="def_btn" size="xl" level="2" onClick={tt("dsdd")}>
                    Тестовое сообщение
                </Button>
                <Button className="def_btn" size="xl" level="2" >
                    Тест
                </Button>
            </Div>
        </Group>
    </Panel>
);
// Home.propTypes = {
//     id: PropTypes.string.isRequired,
//     go: PropTypes.func.isRequired,
//     fetchedUser: PropTypes.shape({
//         photo_200: PropTypes.string,
//         first_name: PropTypes.string,
//         last_name: PropTypes.string,
//         city: PropTypes.shape({
//             title: PropTypes.string,
//         }),
//     }),
// };

export default Home;

In "what".js is the following:
import $ from "jquery";

export function rules(dd) {
    $("#skdsmdksd").html(dd);
}

export function tt(test) {
    if (test !== "" || !test) {
        $(".message").append(`<div class="success_message">
        <p>${test}</p>		
      </div>`);
    } else {
        $(".message").append(`<div class="success_message">
        <p>Отослано!</p>		
      </div>`);
    }
}

export function mess(dat) {
    $("#skdsmdksd").html(dat.access_token);
}

App.js Code
import React from 'react';
import connect from '@vkontakte/vkui-connect';
import { View } from '@vkontakte/vkui';
import '@vkontakte/vkui/dist/vkui.css';
import Home from './panels/Home';
import Persik from './panels/Persik';
import Test from './panels/test';


class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      activePanel: 'home',
      fetchedUser: null,
      ff:null
    };
  }

  componentDidMount() {
    connect.subscribe((e) => {
      console.log(e.detail.type);
      switch (e.detail.type) {
        case 'VKWebAppGetUserInfoResult':
          this.setState({ fetchedUser: e.detail.data });
          break;
        case 'VKWebAppAccessTokenReceived':
          this.setState({ff:e.detail.data});
          console.log(e);
          break;
        default:
          console.log(e.detail.type);
      }
    });
    connect.send('VKWebAppGetUserInfo', {});
  }

  go = (e) => {
    this.setState({ activePanel: e.currentTarget.dataset.to })
  };

  render() {
    return (
      <View activePanel={this.state.activePanel}>
        <Home id="home" ff={this.state.ff} fetchedUser={this.state.fetchedUser} go={this.go} />
        <Persik  id="persik" ff={this.state.ff}  go={this.go} />
        <Test  id="test" ff={this.state.ff}  go={this.go}/>
      </View>
    );
  }
}

export default App;

The problem is this:
When the application is loaded, the scripts from "what" are executed immediately, which should not be.
Ie it turns out that when elements are rendered, all scripts are executed (well, at least it seems to me so)
Is it possible to prevent this somehow?
Thanks in advance for your reply.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-27
@nastyskafomka

When the application is loaded, the scripts from "what" are executed immediately, which should not be.

You call tt yourself when the Home component is rendered:
right like this:
it's even better to write a handler wrapper and pass it to the button:
handler = () => {
  tt("dsdd");
};

In a good way, do not use jQuery at all in React development.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question