1

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

目前我有硬编码的图像名称,图像名称在 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
              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()}
            />
4

2 回答 2

1

看起来你需要调整你的英雄映射:

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));
}
于 2019-08-06T19:18:27.033 回答
0

尝试这个。

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
    };
  }
于 2019-08-06T19:19:22.580 回答