Build a simple shopping platform from scratch (6)

From scratch, build a simple shopping platform (5): https://blog.csdn.net/time_____/article/details/105437534
Project source code (continuous update): https://gitee.com/DieHunter/myCode/ tree/master/shopping

In the fourth article , the file upload on the server side and the back-end function of adding users were implemented and tested. This article mainly implements the functions of uploading avatars and adding users on the front-end

First, we introduce the file upload component in antd and encapsulate it in our component

  • We restrict users to upload only one image. The action in the upload component represents the upload path, which is the address of the upload file we tested in the fourth article. The name is the file identification name, and data is the passed parameter. Here we are Used token

import React from "react";
import { Upload,  message } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import config from "../../config/config";
let {
  UploadName,
  Agreement,
  BaseUrl,
  ServerPort,
  Path,
  UploadKey,
  StorageName,
} = config;
export default class UpdataPic extends React.Component {
  state = {
    fileList: [],
  };
  
  
  handleChange = ({ fileList, file }) => {
    this.setState({ fileList });
    if (file["response"] && file.status == "done") {
      let res = file["response"];
      message.success(res.msg);
    }
    if (file["status"] == "removed") {
      
    }
  };
  render() {
    const { fileList } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div className="ant-upload-text">上传头像</div>
      </div>
    );
    return (
      <div className="clearfix">
        <Upload
          action={Agreement + BaseUrl + ServerPort + Path + UploadName.headPic}
          name={UploadKey.headKey}
          listType="picture-card"
          fileList={fileList}
          onChange={this.handleChange}
          data={
   
   { token: this.$utils.getStorage(StorageName.token) }}
        >
          {fileList.length >= 1 ? null : uploadButton}
        </Upload>
      </div>
    );
  }
}

  • Then we introduce the component on a page to try the effect

After the upload function is implemented, we can start adding users

  • To add a new user, I plan to put it in the drawer component on the right, that is, the Drawer component, and embed the form in the drawer ( modifying users and adding new users are similar, we modify user information directly in the newly added user Drawer Just give the initial value to the form )

  • There are several points to note , 1.antd's form needs to use React.createRef() to load the component. 2. When the form data is assigned the initial value, you need to call the this.formRef.current.setFieldsValue() method of the form. However, there is a pitfall . When the Drawer component is displayed, the form component has not been loaded yet. If you assign the value directly at this time, The assignment will be unsuccessful due to asynchrony. The solution (the official processing method is to use redux global management, here I use the life cycle function to solve it): first enable the pre-loading function in the Drawer component (forceRender, pre-rendering the elements in the Drawer ), and then get the value in the state in the life cycle (componentDidUpdate ), call this.formRef.current.setFieldsValue() (the same as modifying user information)
import React from "react";
import Mail from "../../config/mail";
import {
  Drawer,
  Form,
  Button,
  Col,
  Row,
  Input,
  Select,
  Radio,
  Cascader,
  message,
} from "antd";
import config from "../../config/config";
import City from "../../config/city";
import UpdataPic from "../updata/updata";
const { ServerApi, StorageName, FilePath } = config;
const { Option } = Select;

export default class ListDrower extends React.Component {
  formRef = React.createRef();
  state = {
    visible: false,
    record: {},
  };
  componentDidMount() {
    this.props.onDrowerRef(this);
  }
  componentDidUpdate() {
    this.formRef.current.setFieldsValue(this.state.record);
  }

  showDrawer = () => {//显示Drawer
      this.setState({
        formType: "add",
        visible: false,
        record: {
          sex: "man",
          userType: "user",
          mailurl: "@qq.com",
        },
      });
    this.setState({
      visible: true,
    });
  };
  onClose = () => {//隐藏Drawer
    this.formRef.current.resetFields();
    this.setState({
      visible: false,
      record: null,
    });
  };
  getPic = (data) => {//上传头像后刷新表单头像信息
    this.formRef.current.setFieldsValue({
      headPic: data.headPath,
    });
  };
  delPic = () => {//删除头像后同时删除表单图片信息
    this.formRef.current.setFieldsValue({
      headPic: null,
    });
  };
  sendData(val) {//提交用户信息
    val.token = this.$utils.getStorage(StorageName.token);
    let data = this.$crypto.setCrypto(val);
    let _t = this;
    this.$axios
      .post(ServerApi.user.addUser, { crypto: data })
      .then((res) => {
        switch (res.result) {
          case 1:
            message.success(res.msg);
            _t.onClose();
            _t.props.getUserList();
            break;
          case 0:
            message.warning(res.msg);
            break;
          default:
            // message.warning(res.msg);
            break;
        }
      })
      .catch((err) => {
        message.error("操作失败");
      });
  }
  render() {
    return (
      <Drawer
        title="新增用户"
        width={720}
        onClose={this.onClose}
        visible={this.state.visible}
        forceRender //加上预加载,防止表单异步生成,导致this.formRef.current为空
        bodyStyle={
   
   { paddingBottom: 80 }}
        footer={
          <div
            style={
   
   {
              textAlign: "right",
            }}
          >
            <Button onClick={this.onClose} style={
   
   { marginRight: 20 }}>
              取消
            </Button>
          </div>
        }
      >
        <Form
          layout="vertical"
          hideRequiredMark
          ref={this.formRef}
          onFinish={this.sendData.bind(this)}
        >
          <Row gutter={16}>
            <Col span={10}>
              <Form.Item name="headPic" label="头像">
                <UpdataPic
                  onUpdateRef={(child) => {
                    this.updateChild = child;
                  }}
                  picTarget={this.getPic}
                  picDelete={this.delPic}
                ></UpdataPic>
              </Form.Item>
            </Col>
            <Col span={10}>
              <Form.Item
                name="userType"
                label="用户类型"
                rules={[{ required: true, message: "请选择用户类型" }]}
              >
                <Radio.Group buttonStyle="solid">
                  <Radio.Button value="admin">管理员</Radio.Button>
                  <Radio.Button value="user">用户</Radio.Button>
                </Radio.Group>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: "请输入用户名" }]}
              >
                <Input placeholder="请输入用户名" allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="password"
                label="密码"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password
                  type="password"
                  placeholder="请输入密码"
                  allowClear
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={5}>
              <Form.Item
                name="sex"
                label="性别"
                rules={[{ required: true, message: "请选择性别" }]}
              >
                <Radio.Group buttonStyle="solid">
                  <Radio.Button value="man">男</Radio.Button>
                  <Radio.Button value="woman">女</Radio.Button>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col span={16}>
              <Form.Item label="邮箱">
                <Input.Group compact>
                  <Form.Item
                    name="mailaddress"
                    rules={[{ required: true, message: "请输入正确邮箱" }]}
                  >
                    <Input defaultValue="" allowClear />
                  </Form.Item>
                  <Form.Item
                    name="mailurl"
                    rules={[{ required: true, message: "请选择邮箱类型" }]}
                  >
                    <Select onChange={this.changeMail} style={
   
   { width: 150 }}>
                      {(() => {
                        return Mail.address.map((item) => {
                          return (
                            <Option key={item.mail} value={item.mail}>
                              {item.mail}
                            </Option>
                          );
                        });
                      })()}
                    </Select>
                  </Form.Item>
                </Input.Group>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={16}>
              <Form.Item label="收货地址" required={false}>
                <Input.Group compact>
                  <Form.Item
                    name="alladdress"
                    // rules={[{ required: true, message: "请选择收货地址" }]}
                  >
                    <Cascader options={City} placeholder="请选择收货地址" />
                  </Form.Item>
                  <Form.Item
                    name="address"
                    // rules={[{ required: true, message: "请填写收货地址" }]}
                  >
                    <Input placeholder="请输入详细地址" allowClear />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item name="descript" label="个性签名">
                <Input.TextArea rows={4} placeholder="个性签名" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    );
  }
}
  • Finally, we request the server to try

to sum up

React is a dom optimization framework based on the view display layer. Its global state management plug-in redux globalizes some shared variables, which is equivalent to defining global variables in the native window scope. Although it is convenient, it can be omitted. Place, it’s best to use less

Guess you like

Origin blog.csdn.net/time_____/article/details/105440818