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

时间:2017-10-12 18:17:56

标签: node.js reactjs typescript express rxjs

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

我创建了Quick-List on github来研究这些事情,但我发现了一个问题......

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

我在“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.");
      }

    });
  }
}

我有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;

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

OBS。:不使用角度

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

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

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

  

当列表中的&#34; IndexRoute&#34;类更改,视图也会发生变化。

组件使用的props(从其父级传入)需要根据路由更改进行更改。

更多

  

我对如何做到这一点没有任何想法,如果反应式编程是最好的想法,那就错误了

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

开始