繁体   English   中英

使用动态 Id 更新 firebase 文档中的数据

[英]UPDATE the data on a firebase document using dynamic Id

我在 React-Redux-Firebase 中制作应用程序,但在对 firestore 进行更新时遇到问题。 问题是,当我从 firebase 中选择一个特定的 ID 时,一切正常,但是当我尝试使用动态 ID 时(因为我想通过 Firebase 上生成的 ID 来编辑每个 doc.() 中的数据)它总是会出错.

我认为这个问题可能与处理程序有关,或者可能与文件“EditarUtente.js”上的 map...TO...有关,因为这就是将我在表单中写入的数据发送到“utenteActions.js”的原因。杰斯”

现在我正在使用许多依赖项,包括:

react-redux,
redux,
redux-thunk,
redux-firestore
react-redux-firebase

我把我的组件留在这里供你们检查:

PerfilUtente.js

这是初始文档的“详细信息”页面,我在其中显示信息。 它也作为调度和删除它的按钮是 Id,当我们单击“此处”按钮时,它是我导入我的编辑文件以显示在应用程序上的地方。

    import React from "react";
    import { makeStyles } from "@material-ui/core/styles";
    import Card from "@material-ui/core/Card";
    import Container from "@material-ui/core/Container";
    import ImageAvatars from "./Perfil Utente/perfilUtente";
    import Button from "@material-ui/core/Button";
    import { Grid } from "@material-ui/core";
    import { Link } from "react-router-dom";
    
    import { connect } from "react-redux"; //conecta o component com o redux
    import { firestoreConnect } from "react-redux-firebase";
    import { compose } from "redux";
    import { deleteUtente } from "../Store/Actions/utenteActions";
    import EditarUtente from "./EditarUtente";
    
    import { BrowserRouter as Router } from "react-router-dom";
    import { Route, NavLink } from "react-router-dom";
    
    const useStyles = makeStyles((theme) => ({
      root: {
        flexGrow: 1,
    
        textAlign: "center",
      },
      paper: {
        padding: theme.spacing(2),
        textAlign: "center",
        color: theme.palette.text.secondary,
      },
    }));
    
    const PerfilUtente = (props) => {
      const { utente, deleteUtente } = props;
    
      console.log(props);
    
      let utenteId = props.match.params.id;
    
      console.log(utenteId);
      const classes = useStyles();
    
      if (utente) {
        return (
          <div
            style={{
              background: "rgb(66, 133, 244)",
              width: "100%",
              height: 1000,
            }}
          >
            <Container>
              <div>
                <Card className={classes.root}>
                  <ImageAvatars />
                  <span>Utente ID : {utenteId}</span>
                  <br />
                  <span>Nome : {utente.nome}</span>
                  <br />
                  <span>Estado Civil : {utente.eCivil}</span>
                  <br />
                  <Grid container fluid spacing={2}>
                    <Grid item xs={12} sm={6}>
                      <Link to={"/Alimentação"} style={{ textDecoration: "none" }}>
                        <Button
                          variant="contained"
                          color="primary"
                          style={{ width: "90%", height: 80, marginLeft: 25 }}
                        >
                          Alimentação
                        </Button>
                      </Link>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <Link to={"/Informações"} style={{ textDecoration: "none" }}>
                        <Button
                          variant="contained"
                          color="primary"
                          style={{ width: "90%", height: 80, marginRight: 25 }}
                        >
                          Informações
                        </Button>
                      </Link>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <Link to={"/Saúde"} style={{ textDecoration: "none" }}>
                        <Button
                          variant="contained"
                          color="primary"
                          style={{
                            width: "90%",
                            height: 80,
                            marginLeft: 25,
                            marginTop: 6,
                          }}
                        >
                          Saúde
                        </Button>
                      </Link>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <Link to={"/Bem-Estar"} style={{ textDecoration: "none" }}>
                        <Button
                          variant="contained"
                          color="primary"
                          style={{
                            width: "90%",
                            height: 80,
                            marginRight: 25,
                            marginTop: 6,
                            marginBottom: 30,
                          }}
                        >
                          Bem-Estar
                        </Button>
                      </Link>
                    </Grid>
                  </Grid>
                  <Router>
                    <Route path="/editarUtente/:id" component={EditarUtente} />
    
                    <div key={utente.id}>
                      <NavLink
                        to={"/editarUtente/" + utenteId}
                        exact
                        activeStyle={{ color: "green" }}
                      >
                        {/* <EditarUtente utenteId={utenteId} /> */}
                        HEre
                      </NavLink>
                    </div>
                    <br />
                  </Router>
                  <br />
                  <button
                    onClick={() => {
                      deleteUtente(utenteId);
                      props.history.push("/");
                    }}
                  >
                    Delete
                  </button>
                </Card>
              </div>
            </Container>
          </div>
        );
      } else {
        return (
          <div>
            <p> A carregar Utente...</p>
          </div>
        );
      }
    };
    
    const mapStateToProps = (state, ownProps) => {
      const id = ownProps.match.params.id;
      const utentes = state.firestore.data.utentes;
      const utente = utentes ? utentes[id] : null;
    
      return {
        utente: utente,
      };
    };
    
    const mapDispatchToProps = (dispatch) => {
      return {
        deleteUtente: (utenteId) => dispatch(deleteUtente(utenteId)),
      };
    };
    
    export default compose(
      connect(mapStateToProps, mapDispatchToProps),
      firestoreConnect([{ collection: "utentes" }])
    )(PerfilUtente);

EditarUtente.js

这是我拥有在 firestore 中编辑我的文档的所有内容的组件。

import React, { Component } from "react";
import { connect } from "react-redux"; //para que o component tenha acesso á redux store
import { updateUtente } from "../Store/Actions/utenteActions";

import { firestoreConnect } from "react-redux-firebase";
import { compose } from "redux";

import { withRouter } from "react-router-dom";

class EditarUtente extends Component {
  state = {
    nome: "",
    idade: "",
    eCivil: "",
  };
  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value,
    });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.updateUtente(this.state);
  };

  render() {
    const utenteId = this.props.match.params.id;
    console.log(utenteId);

    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          {/* <label htmlFor="nome">Nome:</label>
          <input
            type="hiden"
            disabled
            id="nome"
            onChange={this.handleChange}
            value={utenteId}
          />
          <br /> */}
          <label htmlFor="nome">Nome:</label>
          <input type="text" id="nome" onChange={this.handleChange} />
          <br />
          <label htmlFor="idade">Idade:</label>
          <input type="text" id="idade" onChange={this.handleChange} />
          <br />
          <label htmlFor="eCivil">Estado Civil:</label>
          <input type="text" id="eCivil" onChange={this.handleChange} />
          <br />
          <button
          // onClick={() => {
          //   updateUtente(utenteId);
          // }}
          >
            Update
          </button>
          >
        </form>
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  console.log(state);
  const id = ownProps.match.params.id;
  console.log(id);
  const utentes = state.firestore.data.utentes;
  console.log(utentes);
  const utente = utentes ? utentes[id] : null;

  return {
    utente: utente,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    updateUtente: (utente) => dispatch(updateUtente(utente)),
  };
};

export default compose(
  connect(mapStateToProps, mapDispatchToProps),
  firestoreConnect([{ collection: "utentes" }]),
  withRouter
)(EditarUtente);

utenteActions.js

这是来自 redux 的 Action Creator,用于管理所有事情以使用实际操作和有效负载分派操作

export const createUtente = (utente) => {
  return (dispatch, getState, { getFirebase, getFirestore }) => {
    //make async call to database
    const firestore = getFirestore();
    firestore
      .collection("utentes")
      .add({
        ...utente,
        authorFirstName: "Lar",
        authorId: 123,
        createdAt: new Date(),
      })
      .then(() => {
        dispatch({ type: "CREATE_UTENTE", utente });
      })
      .catch((err) => {
        dispatch({ type: "CREATE_UTENTE_ERROR", err });
      });

    dispatch({ type: "CREATE_UTENTE", utente: utente });
  };
};

export const deleteUtente = (utenteId) => {
  return (dispatch, getState, { getFirebase, getFirestore }) => {
    //make async call
    console.log(utenteId);
    const firestore = getFirestore();

    firestore
      .delete({ collection: "utentes", doc: utenteId })
      .then(() => {
        dispatch({ type: "DELETE_UTENTE", utenteId });
      })
      .catch((err) => {
        dispatch({ type: "DELETE_UTENTE_ERROR", err });
      });
  };
};

export const updateUtente = ({ utente }) => {
  return (dispatch, getState, { getFirebase, getFirestore }) => {
    //make async call to database

    const firestore = getFirestore();
    firestore
      .collection("utentes")
      .doc("FPAY4Bw5VmJeGVINkQXc")
      .update({
        ...utente,
        authorFirstName: "Lar",
        authorId: 123,
        createdAt: new Date(),
      })
      .then(() => {
        dispatch({ type: "UPDATE_UTENTE", utente });
      })
      .catch((err) => {
        dispatch({ type: "UPDATE_UTENTE_ERROR", err });
      });

    dispatch({ type: "UPDATE_UTENTE", utente: utente });
  };
};

utenteReducer.js

这是 Reducer 组件。

const initState = {
  utentes: [
    { id: "", title: "", content: "" },
    { id: "", title: "", content: "" },
    { id: "", title: "", content: "" },
  ],
};
const utenteReducer = (state = initState, action) => {
  // console.log(action);
  switch (action.type) {
    case "CREATE_UTENTE":
      console.log("Utente criado!", action.utente);
      return state;
    case "CREATE_UTENTE_ERROR":
      console.log("Erro na criação do utente", action.err);
      return state;
    case "DELETE_UTENTE":
      console.log("Utente Apagado!", action.utente);
      return state;
    case "DELETE_UTENTE_ERROR":
      console.log("Erro ao apagar utente", action.err);
      return state;
    case "UPDATE_UTENTE":
      console.log("Utente Atualizado!", action.utente);
      return state;
    case "UPDATE_UTENTE_ERROR":
      console.log("Erro ao atualizar utente", action.err);
      return state;
    default:
      return state;
  }
  // return state;
};
export default utenteReducer;

我希望有人能真正帮助我:! 谢谢你的时间! :)

如果有人想联系我,这是我的 Discord:Rogerini Mercatori#6854

我通过 state 传递 Id 解决了所有问题,然后,当我发送操作时,它进入 Action Creator 的 object 类型,所以当我们想要使用该 id 时,我们可以在发送的 object 中访问!

希望我能帮助那里的人!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM