Восстановить начальное значение null при нажатии на кнопку редактирования - PullRequest
1 голос
/ 19 февраля 2020

Я пытаюсь редактировать форму. После первого рендеринга я не получаю существующие данные из базы данных. Из-за состояния ноль. Если я нажимаю на вторую кнопку, появляются первые данные. (Из-за состояния ноль. Если я нажимаю на вторую кнопку, появляются первые данные.)

Редуктор:

const intialState ={ channel:null}

Пожалуйста, нажмите здесь для изображения

enter image description here

// Компонент формы

    import React, { Fragment } from "react";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";

const FormChannel = ({ channelData, ouSubmit, open }) => {
  let [formData, setFromData] = React.useState({
    channel: channelData ? channelData.channel : "",
    channelName: channelData ? channelData.channelName : "",
    introduction: channelData ? channelData.introduction : "",
    language: channelData ? channelData.language : "",
    keywords: channelData ? channelData.keywords : ""
  });
  const { channel, channelName, introduction, language, keywords } = formData;

  const handleClose = () => {
    ouSubmit(formData);
    setFromData({
      channel: "",
      channelName: "",
      introduction: "",
      language: "",
      keywords: ""
    });
  };

  const handleChange = channel => e => {
    setFromData({ ...formData, [channel]: e.target.value });
  };

  const view = (
    <Fragment>
      <Dialog
        open={open}
        onClose={handleClose}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Create Channel</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            value={channel}
            onChange={handleChange("channel")}
            id="channel"
            label="Name"
            type="emachannelil"
            margin="normal"
            variant="outlined"
            fullWidth
          />
          <TextField
            value={channelName}
            onChange={handleChange("channelName")}
            id="channelName"
            label="Channel Name"
            type="text"
            margin="normal"
            variant="outlined"
            fullWidth
          />
          <TextField
            label="Language"
            id="language"
            value={language}
            onChange={handleChange("language")}
            type="text"
            margin="normal"
            variant="outlined"
            fullWidth
          />
          <TextField
            value={introduction}
            onChange={handleChange("introduction")}
            id="introduction"
            label="Introduction"
            type="text"
            margin="normal"
            variant="outlined"
            fullWidth
          />
          <TextField
            value={keywords}
            onChange={handleChange("keywords")}
            id="kewords"
            label="Keywords"
            type="text"
            margin="normal"
            variant="outlined"
            fullWidth
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} color="primary">
            Cancel
          </Button>
          <Button onClick={handleClose} color="primary" variant="contained">
            Create
          </Button>
        </DialogActions>
      </Dialog>
    </Fragment>
  );
  return <Fragment>{view}</Fragment>;
};
export default FormChannel

Редактировать

import React, { Fragment } from "react";
import { connect } from "react-redux";
import { Button } from "@material-ui/core";
import FormChannel from "./Form";
const EditChannel = ({ channels: { channel }, open, setOpen }) => {
  console.log(channel);
  return (
    <Fragment>
      <FormChannel
        open={open}
        channelData={channel}
        ouSubmit={formData => {
          setOpen(false);
          console.log(formData);
        }}
      />
    </Fragment>
  );
};
const mapStateToProps = (state, props) => {
  console.log(state);
  return {
    channels: state.channels
  };
};
export default connect(mapStateToProps)(EditChannel);

карта

import React, { Fragment } from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Typography, Button } from "@material-ui/core";
import Avatar from "@material-ui/core/Avatar";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { channelFollow, channelFetchById } from "../../../redux/action/channel";
import EditChannel from "../../Channels/List/Edit";

const useStyles = makeStyles(theme => ({
  card: {
    flexGrow: 1
  },
  img: {
    height: "60%",
    overflow: "hidden",
    width: "100%"
  },

  link: {
    textDecoration: "none",
    color: "black"
  },
  link1: {
    textDecoration: "none",
    color: "white"
  },
  root: {
    display: "flex",
    "& > *": {
      margin: theme.spacing(0.5)
    },
    justifyContent: "center"
  },
  button: {
    display: "flex",
    justifyContent: "center"
  },
  text: {
    fontWeight: "bold",
    fontSize: 15
  },
  text1: {
    color: "gray",
    fontSize: 15
  },
  bigAvatar: {
    width: 140,
    height: 140
  },
  buttons: {
    marginRight: 5
  }
}));

const ChannelCard = props => {
  const classes = useStyles();
  const { channel, channelFetchById } = props;
  const [open, setOpen] = React.useState(false);
  const handleClickOpen = () => {
    setOpen(true);
  };
  const view = (
    <div className={classes.card}>
      <Link to={`/channels/${channel._id}`} className={classes.link}>
        <div className={classes.root}>
          <Avatar
            alt="Remy Sharp"
            src={channel.avatar}
            className={classes.bigAvatar}
          />
        </div>

        <div className={classes.title}>
          <Typography
            variant="subtitle1"
            align="center"
            className={classes.text}
          >
            {channel.channelName}
          </Typography>
          <Typography variant="body2" align="center">
            {channel.introduction}
          </Typography>
        </div>
      </Link>
      <Typography variant="body2" align="center" className={classes.text1}>
        {channel.follows ? channel.follows.length : 0} followers <br />
        Language:{channel.language}
      </Typography>
      <div className={classes.center}>
        <div className={classes.button}>
          <div className={classes.buttons}>
            <Button
              variant="contained"
              color="primary"
              onClick={() => {
                channelFetchById(channel._id);
                handleClickOpen();
              }}
            >
              Edit
            </Button>
            {open ? <EditChannel setOpen={setOpen} open={open} /> : ""}
          </div>
          <div>
            <Button color="primary" variant="contained">
              Delete
            </Button>
          </div>
        </div>

        <br />
      </div>
    </div>
  );
  return <Fragment>{view}</Fragment>;
};
export default connect(null, { channelFollow, channelFetchById })(ChannelCard);

Редуктор

    import {
  CHANNEL_FETCH,
  CHANNEL_FETCH_BY_ID,
  CHANNEL_UNFOLLOWED,
  CHANNEL_EDIT
} from "../action/typeof";
const initialState = {
  channels: [],
  channel: null,
  loading: true
};
export default (state = initialState, action) => {
  const { payload } = action;
  switch (action.type) {
    case CHANNEL_FETCH:
      return { ...state, channels: payload, loading: false };
    case CHANNEL_FETCH_BY_ID:
      return {
        ...state,
        channel: payload,
        loading: false
      };
    case CHANNEL_UNFOLLOWED:
      return {
        ...state,
        channelUnfollowedUser: payload,
        loading: false
      };
    case CHANNEL_EDIT:
      const channelEdit = state.channes.map(single =>
        single._id === payload.id ? { single, ...payload.data } : single
      );
      return {
        ...state,
        channels: channelEdit,
        loading: false
      };

    default:
      return state;
  }
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...