E
E
Evgeny Ivanov2021-10-28 13:14:14
React
Evgeny Ivanov, 2021-10-28 13:14:14

How is a message displayed (rendered) in my React project?

I'm learning React from video tutorials. Until lesson 35, everything was simple and clear.
Simple, test, educational project. Everything is working.
It's probably correct to write questions to the author of the video course (I taught you myself, so answer), but I'll try to write the course here. the question is simple and in code.

In a tutorial project, we just figured out props forwarding. We moved the business logic to the state.js file (an analogue of the future reducer) and began to transfer functions to components (callbacks).
The task was to render the project by calling a function. To do this, we created the observer function (named after the pattern of the same name and performs this role).

The question is - how is a message displayed (rendered) in my React project? For what?
How does this mechanism work now (I understand callbacks and forwarding props)?
More specifically rerenderEntireTree (there are two of them in state.js and in index.js).

PS
It seems that there is a lot of code, but half of it is import and the code is very simple (literally 2-3 steps).

State.js file An analogue of the future reducer.

/* Заглушка - функция перерисовки. Для чего она тут непонятно. Но без неё не работает.  Одноименная функция есть в index.js */
let rerenderEntireTree =()=>{
    console.log('state changed');
}

/*  Тут хранится вся информация, аналог редьюсера в учебном примере  */
let state = {


    /* Страница профиля - вот сюда и добавляются посты */
    profilePage: {

        /* Информация для сообщений - текст сообщений и лайки  */
        posts: [
            {id: 1, message: "Пост 1", likesCount: 1},
            {id: 2, message: "Пост 2", likesCount: 2}
        ],
        newPostText : 'MynewPostText value',
    },

    /* Страница сообщений - это смотреть не нужно, вопрос не про это */
    dialogsPage: {

        /* Информация для сообщений в диалогах */
        messages: [
            {id: 1, message: "Сообщение 1"},
            {id: 2, message: "Сообщение 2"},
            {id: 3, message: "Сообщение 3"},
        ],

        /* Информация для диалогов*/
        dialogs: [
            {id: 1, name: "Иван"},
            {id: 2, name: "Петр"},
            {id: 3, name: "Света"}
        ],

    },


}

/*  Основная функция добавления сообщения  */
export let addPost = () =>{
    let newPost ={
        id:5,
        message: state.profilePage.newPostText,
        likesCount: 0,
    }
    state.profilePage.posts.push(newPost);
    state.profilePage.newPostText=''; 
    rerenderEntireTree(state); /*  Вызов rerenderEntireTree - но какой (их две в разных файлах )и почему работает, когда выше она заглушка? */
}

export let updateNewPostText = (newText) =>{

    state.profilePage.newPostText = newText;
    rerenderEntireTree(state);
}

export  const  subscribe = (observer) => {
    rerenderEntireTree = observer;
}

export default state;


index.js file
import App from './App';
import state, {subscribe} from "./redux/state";
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';


import {addPost, updateNewPostText} from './redux/state';
import {BrowserRouter} from "react-router-dom";

/* Ещё одна функция rerenderEntireTree, одноименная функция-заглушка есть в state.js */
let rerenderEntireTree =(state) =>
{
    ReactDOM.render(
        <React.StrictMode>
            <BrowserRouter>
                <App
                    state={state}
                    addPost={addPost}
                    updateNewPostText={updateNewPostText}

                />
            </BrowserRouter>
        </React.StrictMode>,
        document.getElementById('root')
    );
}


/* Зачем и когда это вызывается? Что тут ререндерится? */
rerenderEntireTree(state);

/* Зачем и когда это вызывается? Что тут ререндерится? */
subscribe(rerenderEntireTree);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();


app.js file
import React from 'react';
import './App.css';
import Header from './components/Header/Header';
import Navbar from './components/Navbar/Navbar';
import Profile from './components/Profile/Profile';
import Dialogs from './components/Dialogs/Dialogs';
import {BrowserRouter, Route} from "react-router-dom";
import {addPost, updateNewPostText} from "./redux/state";

const App = (props) => {

return (

<div className="App">
<div className="wrapper">

<Header/>
<Navbar/>

<div className="app-wrapper-content">

<Route path="/dialogs" render={() => <Dialogs state={props.state.dialogsPage}

/>}/>
<Route path="/profile" render={() => <Profile profilePage={props.state.profilePage}
  addPost={props.addPost}
  updateNewPostText={props.updateNewPostText}

/>}/>

</div>
</div>
</div>
);

}
export default App;


Profile.js file - this is where messages are added and displayed
import React from 'react';
import css from './Profile.module.css';
import MyPosts from './MyPosts/MyPosts';

/* Компонента отображающая информацию о профиле */
import ProfileInfo from './MyPosts/ProfileInfo/ProfileInfo';
import {addPost} from "../../redux/state";


const Profile = (props) => {



return (

<div>

<div className={css.Profile}>

<ProfileInfo/>


</div>


<MyPosts posts={props.profilePage.posts}
 addPost={props.addPost}
 newPostText={props.profilePage.newPostText}
 updateNewPostText={props.updateNewPostText}

/>
</div>
);
}
export default Profile;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question