反应:如何将存储在Firebase存储中的图像分配给存储在Firebase数据库中的项目?

问题描述 投票:0回答:2

我正在渲染Firebase数据库中存储的项目列表,我想知道是否可以为列表中的每个不同项目分配一个不同的图像(存储在Firebase存储中)。

我已经实现了上传功能,该功能可以随后显示最近上传的文件,但是我不知道如何为数据库中的项目分配图像,该图像在渲染后会永久显示在项目旁边。

AdminPanel组件代码:

class AdminPanel extends Component {
  constructor() {
    super();
    this.state = {
      companyName: '',
      ownerName: '',
      items: [],
      search: '',
      image: '',
      imageURL: '',
      progress: 0,
      images: null
    }

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  handleSubmit(e) {
    e.preventDefault();
    const itemsRef = firebase.database().ref('items');
    const item = {
      companyNameObj: this.state.companyName,
      ownerNameObj: this.state.ownerName
    }
    itemsRef.push(item);
    this.setState({
      companyName: '',
      ownerName: ''
    });
  }

  componentDidMount() {
    const itemsRef = firebase.database().ref('items');

    itemsRef.on('value', (snapshot) => {
      let items = snapshot.val();
      let newState = [];
      for (let item in items) {
        newState.push({
          id: item,
          companyNameObj: items[item].companyNameObj,
          ownerNameObj: items[item].ownerNameObj
        });
      }
      this.setState({
        items: newState
      });
    });
  }

  removeItem(itemId) {
    const itemRef = firebase.database().ref(`/items/${itemId}`);
    itemRef.remove();
  }

  handleUploadStart = () => {
    this.setState({
      progress: 0
    })
  }

  handleUploadSuccess = filename => {
    this.setState({
      image: filename,
      progress: 100
    })

    firebase.storage().ref('images').child(filename).getDownloadURL().then(url => this.setState({
      imageURL: url
    }))
  }

  render() {

    var image = this.state.imageURL;

    let filteredItems = this.state.items.filter(
      (item) => {
        return item.companyNameObj.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1;
      }
    );

    return (
      <div>
        <h1>ADMIN PANEL</h1>
        <form onSubmit={this.handleSubmit}>
          <input type="text" name="ownerName" placeholder="Company name: " onChange={this.handleChange} value={this.state.ownerName} />
          <input type="text" name="companyName" placeholder="Owned by: " onChange={this.handleChange} value={this.state.companyName} />
          <button>Add Company</button>
          <input type="text" name="search" placeholder="Search: " onChange={this.handleChange} value={this.state.search} />
        </form>

          <label>
            <p>Progress: </p>
            {this.state.progress}
          </label>

          <label>
            <p>Image: </p>
            {this.state.image && <img src={this.state.imageURL} />}
          </label>

          <FileUploader
            accept='image/*'
            name='image'
            storageRef={firebase.storage().ref('images')}
            onUploadStart={this.handleUploadStart}
            onUploadSuccess={this.handleUploadSuccess}
          />

          <ul>
            {filteredItems.map((item) => {
              return (
                <li key={item.id}>
                  <h3>{item.companyNameObj}</h3>
                  <p>Owned by: {item.ownerNameObj}</p>
                  {<img src={this.state.imageURL} />}
                  <button onClick={() => this.removeItem(item.id)}>Remove Item</button>
                </li>
              )
            })}
          </ul>
      </div>
    );
  }
}

export default AdminPanel;
reactjs firebase firebase-realtime-database firebase-storage
2个回答
0
投票

您需要从FirebaseStorage获取URL并将其放置为RealtimeDatabase或Firestore对象。


0
投票

由于@Juanje的回答,我设法实现了解决方案:

您需要从FirebaseStorage获取URL并将其放置为RealtimeDatabase或Firestore对象。

我将图像URL映射到我的handleSubmit(e)方法中的图像对象,然后通过我的componentDidMount()方法将该URL对象推送到数据库中,如下所示:

  handleSubmit(e) {
    e.preventDefault();
    const itemsRef = firebase.database().ref('items');
    const item = {
      companyNameObj: this.state.companyName,
      ownerNameObj: this.state.ownerName,
      imageObj: this.state.imageURL
    }
    itemsRef.push(item);
    this.setState({
      companyName: '',
      ownerName: '',
    });

    console.log(item);
  }

  componentDidMount() {
    const itemsRef = firebase.database().ref('items');

    itemsRef.on('value', (snapshot) => {
      let items = snapshot.val();
      let newState = [];
      for (let item in items) {
        newState.push({
          id: item,
          companyNameObj: items[item].companyNameObj,
          ownerNameObj: items[item].ownerNameObj,
          imageObj: items[item].imageObj
        });
      }
      this.setState({
        items: newState
      });
    });
  }

为了渲染URL,我在映射列表中添加了一个标签,并传递了包含Firebase存储作为源的imageObj,如下所示:

          <ul>
            {filteredItems.map((item) => {
              return (
                <li key={item.id}>
                  <h3>{item.companyNameObj}</h3>
                  <p>Owned by: {item.ownerNameObj}</p>
                  <img src={item.imageObj} />
                  <button onClick={() => this.removeItem(item.id)}>Remove Item</button>
                </li>
              )
            })}
          </ul>
© www.soinside.com 2019 - 2024. All rights reserved.