如何从文件池的状态中提取图像名称

How to pull image name from state for file pond

当我导航到特定页面时,我希望用我已经上传的图像重新填充文件池塘图像,图像名称在数据库中。

目前我对图像名称进行了硬编码,图像名称在 componentDidMount 中设置的状态下可用,但文件池的状态也正在设置,老实说这让我有点困惑。

所以,这是硬编码的时候:

class HomeBannerForm extends InputForm {
  async componentDidMount() {
    const { data: hero } = await getHero();
    this.setState({ data: this.mapToViewModel(hero) });
  }

      state = {
        data: {
          title: "",
          bgImg: ""
        },
        errors: {},
        files: [
          {
            source: "myImage.jpg",
            options: {
              type: "local"
            }
          }
        ]
      };

  mapToViewModel(hero) {
    return {
      id: hero._id,
      title: hero.title,
      bgImg: hero.bgImg
    };
  }

所以,我需要将 myImage.jpg 更改为来自 componentDidMount 的状态,即:来自数据库的名称。这显然行不通。

    files: [
      {
        source: this.state.data.bgImg
        options: {
          type: "local"
        }
      }
    ]

Filepond 组件代码:

            <FilePond
              ref={ref => (this.pond = ref)}
              files={this.state.files}
              allowMultiple={false}
              maxFiles={1}
              instantUpload={false}
              name="bgImg"
              server={{
                process: "http://localhost:8000/api/hero/",
                load: "http://localhost:8000/img/"
              }}
              oninit={() => this.handleInit()}
              onupdatefiles={fileItems => {
                // Set currently active file objects to this.state
                this.setState({
                  files: fileItems.map(fileItem => fileItem.file)
                });
              }}
              // callback for successfully uploaded image
              onprocessfile={() => this.uploadComplete()}
            />

看来您需要调整英雄映射:

mapToState(hero) {
   return {
     data: {
       title: hero.title,
       bgImg: hero.bgImg
     },
     errors: {},
     files: [
       {
         source: hero.bgImg,
         options: {
           type: "local"
        }
      }
    ]
  };
}
async componentDidMount() {
    const { data: hero } = await getHero();
    this.setState(this.mapToState(hero));
}

试试这个。

class HomeBannerForm extends InputForm {

state = {
        data: {
          title: "",
          bgImg: ""
        },
        errors: {},
        files: [
          {
            source: "myImage.jpg",
            options: {
              type: "local"
            }
          }
        ]
      };

  async componentDidMount() {
    const { data: hero} = await getHero();
this.setState(prevState => ({
      data: this.mapToViewModel(hero),
      files: prevState.files.map(obj => {
        Object.assign(obj, { source: hero.bgImg });
      })
    }));

  }



  mapToViewModel(hero) {
    return {
      id: hero._id,
      title: hero.title,
      bgImg: hero.bgImg
    };
  }