Skip to content

基础数据回填

image.png

操作步骤

  1. 获取文章id
  2. 根据文章id获取文章数据
  3. 设置表单数据
  4. 渲染表单
jsx
const Publish = () => {
  // 回填数据
  const [searchParams] = useSearchParams();
  const articleId = searchParams.get("id");
  const [form] = Form.useForm();
  useEffect(() => {
    async function getArticle() {
      const res = await http.get(`/mp/articles/${articleId}`);
      const { cover, ...formValue } = res.data;
      // 设置表单数据
      form.setFieldsValue({ ...formValue, type: cover.type });
    }
    if (articleId) {
      // 拉取数据回显
      getArticle();
    }
  }, [articleId, form]);

  return <Form form={form} />;
};

回填封面信息

image.png

操作步骤

  1. 回填表单数据
  2. 回填封面图片
javascript
useEffect(() => {
  async function getArticle() {
    const res = await http.get(`/mp/articles/${articleId}`);
    const { cover, ...formValue } = res.data;
    // 1. 回填表单数据
    form.setFieldsValue({ ...formValue, type: cover.type });
    // 2. 回填封面图片
    setImageType(cover.type); // 封面类型
    setImageList(cover.images.map((url) => ({ url }))); // 封面list
  }
  if (articleId) {
    getArticle();
  }
}, [articleId, form]);

适配不同状态下的文案

根据文章id获取判断

jsx
{
  /* 面包屑导航 */
}
<Breadcrumb
  items={[
    ...
    {
      title: (
        <>
          <FormOutlined />
          <span>{articleId ? "编辑文章" : "发布文章"}</span>
        </>
      ),
    },
  ]}
/>;

更新文章

jsx
// 确定发布
  const onFinish = (values) => {
    console.log("Success:", values);
    // 校验图片类型和数量是否吻合
    if (imageType > 0 && imageList.length !== imageType) {
      message.error("请上传正确的图片数量!");
      return;
    }
    const { channel_id, content, title } = values;
    const params = {
      channel_id,
      content,
      title,
      cover: {
        type: imageType,
        // 根据状态处理图片地址
        images: imageList.map((item) => {
          if (item.response) {
            return item.response.data.url; // 处理图片上传地址
          } else {
            return item.url; // 处理图片回显地址
          }
        }),
      },
    };
    if (articleId) {
      // 修改
      http
        .put(`/mp/articles/${articleId}?draft=false`, params)
        .then((res) => {
          console.log(res);
          if (res.message === "OK") {
            message.success("修改成功!");
          } else {
            message.error(res.message || "修改失败!");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      // 新增
      ...
    }

  };