如何在数据更改时更新视图

时间:2023-01-07 07:25:40

I'm trying to learn about a lot of stuff like: Typescript, Express and my new "obsessions" REACT and RXJS.

我正在尝试学习很多东西,比如:Typescript,Express和我的新“迷恋”REACT和RXJS。

I created a Quick-List on github to study these things, but I found a question...

我在github上创建了一个快速列表来研究这些东西,但我发现了一个问题......

"How to update a view in react when data changes"

“如何在数据发生变化时更新视图”

I have an object "List" on the class "IndexRoute":

我在“IndexRoute”类上有一个对象“List”:

import { NextFunction, Request, Response, Router } from "express";
import { List } from "../model/list";
import { Person } from "../model/person";
import * as _ from "lodash";

/**
 * Classe responsável por gerenciar as rotas de Index.
 */
export class IndexRoute {

  private router: Router;
  private list: List; <----[HERE]----

  /**
   * Constructor
   *
   * @class IndexRoute
   * @constructor
   */
  constructor(router: Router) {

    this.router = router;
    this.createList();
    this.routesForGET();
    this.routesForPOST();
    this.routesForPUT();
    this.routesForDELETE();
  }

  private createList() {
    this.list = new List();
    this.list.addPerson(new Person("111", "Joao", 1));
    this.list.addPerson(new Person("1325", "Maria", 10));
    this.list.addPerson(new Person("1564", "José", 25));
  }

  private routesForGET() {

    //Get Rota padrão (index)
    this.router.get("/", (req: Request, res: Response) => {

      var person: Person = this.list.getPersonByCPF("111");

      //set options
      let options: Object = {
        "title": "Express",
        "name": JSON.stringify(this.list.getList())
      };

      var view: string = "index";
      res.render(view, options);
    });
  }

  private routesForPOST() {

    //Adicionar uma nova person via REST
    this.router.post("/", (req: Request, res: Response) => {

      if (_.isEmpty(req.body)) {
        res.status(400).send("Não foi possivel adicionar o elemento, verifique os parametros.");
      } else {

        var cpf: string = req.params.cpf;

        var person = new Person(
          req.body.cpf,
          req.body.name,
          req.body.age
        );

        this.list.addPerson(person);
        res.send("Elemento adicionado com sucesso.");
      }
    });

    //Visualizar uma person com base no cpf
    this.router.post("/:cpf", (req: Request, res: Response) => {

      var cpf: string = req.params.cpf;
      var person: Person = this.list.getPersonByCPF(cpf);

      if (_.isEmpty(person)) {
        res.status(400).send("Não foi possivel encontrar o elemento.");
      } else {
        res.json(person);
      }

    });

    //Exibir body
    this.router.post("/get/list", (req: Request, res: Response) => {

      var l: Person[] = this.list.getList();
      if(_.isEmpty(l)){
        res.status(400).send("Lista vazia.");
      }else{
        res.json(l);
      }

    });

    //Exibir body
    this.router.post("/get/body", (req: Request, res: Response) => {
      res.send(JSON.stringify(req.body));
    });
  }

  private routesForPUT() {

    //Atualizar uma person com base no cpf
    this.router.put("/:cpf", (req: Request, res: Response) => {

      if (_.isEmpty(req.body)) {
        res.status(400).send("Não foi possivel adicionar o elemento, verifique os parametros.");
      } else {

        var cpf: string = req.params.cpf;

        var person = new Person(
          req.body.cpf,
          req.body.name,
          req.body.age
        );

        if (this.list.updatePersonByCPF(cpf, person)) {
          res.send("Elemento atualizado com sucesso.");
        } else {
          res.status(400).send("Não foi possivel atualizar o elemento,     verifique os parametros.");
        }

      }

    });
  }

  private routesForDELETE() {

    //Remover uma person com base no cpf
    this.router.delete("/:cpf", (req: Request, res: Response) => {

      var cpf: string = req.params.cpf;

      if (this.list.removePersonByCPF(cpf)) {
        res.send("Elemento removido com sucesso.");
      } else {
        res.status(400).send("Não foi possivel remover o elemento, verifique os parametros.");
      }

    });
  }
}

And I have the REACT component:

我有REACT组件:

var React = require('react');
var DefaultLayout = require('./layouts/default');

class HelloMessage extends React.Component {
  render() {
    return (
      <DefaultLayout title={this.props.title}>
        <div>Hello {this.props.name}</div>
      </DefaultLayout>
    );
  }
}

module.exports = HelloMessage;

My objective is: When the list in "IndexRoute" class changes, the view changes too.

我的目标是:当“IndexRoute”类中的列表发生更改时,视图也会更改。

OBS.: Without use angular.

OBS:不使用角度。

But there is my main problem... I don't have any idea about how to do it, idk if reactive programming is the best idea, idk if i have to use react-native, exist a lot of tools to be used but idk what is the best for this scenario.

但是我的主要问题是......我对如何做到这一点没有任何想法,如果反应式编程是最好的想法,那就是idk,如果我必须使用react-native,那么存在很多工具要使用但是idk这个场景最好的是什么。

I know that angular can solve it but i like to learn another way.

我知道有角度可以解决它,但我喜欢学习另一种方式。

2 个解决方案

#1


0  

When the list in "IndexRoute" class changes, the view changes too.

当“IndexRoute”类中的列表更改时,视图也会更改。

The props used by the component (passed in from its parent) need to change based on route change.

组件使用的道具(从其父项传入)需要根据路径更改进行更改。

More

I don't have any idea about how to do it, idk if reactive programming is the best idea

我不知道如何做到这一点,如果反应性编程是最好的想法,那就是idk

Walk before running. Start with hello world https://reactjs.org/docs/hello-world.html

跑步前走路。从hello world https://reactjs.org/docs/hello-world.html开始

#2


0  

I studied more and know how to solve it:

我学的更多,知道如何解决它:

1 - Stopping to use express-react-views, it doesn't support mount views on the client.

1 - 停止使用express-react-views,它不支持客户端上的挂载视图。

2 - I have a route that return the list elements, I'll catch them with fetch() and update the view with setState().

2 - 我有一个返回列表元素的路由,我将使用fetch()捕获它们并使用setState()更新视图。

Thx for all, and if someone saw anything wrong in my solution, please tell me to improve more. :)

对所有人来说,如果有人在我的解决方案中看到任何错误,请告诉我改进。 :)

#1


0  

When the list in "IndexRoute" class changes, the view changes too.

当“IndexRoute”类中的列表更改时,视图也会更改。

The props used by the component (passed in from its parent) need to change based on route change.

组件使用的道具(从其父项传入)需要根据路径更改进行更改。

More

I don't have any idea about how to do it, idk if reactive programming is the best idea

我不知道如何做到这一点,如果反应性编程是最好的想法,那就是idk

Walk before running. Start with hello world https://reactjs.org/docs/hello-world.html

跑步前走路。从hello world https://reactjs.org/docs/hello-world.html开始

#2


0  

I studied more and know how to solve it:

我学的更多,知道如何解决它:

1 - Stopping to use express-react-views, it doesn't support mount views on the client.

1 - 停止使用express-react-views,它不支持客户端上的挂载视图。

2 - I have a route that return the list elements, I'll catch them with fetch() and update the view with setState().

2 - 我有一个返回列表元素的路由,我将使用fetch()捕获它们并使用setState()更新视图。

Thx for all, and if someone saw anything wrong in my solution, please tell me to improve more. :)

对所有人来说,如果有人在我的解决方案中看到任何错误,请告诉我改进。 :)