1

我正在使用 react-redux-firebase。这就是用户提交表单后我的 firebase 数据的样子: 在此处输入图像描述

它将信息推送到“联系人”,将图像推送到“uploadedFiles”(也用于文件存储路径)。我真的很想把它作为一个项目。就像是:

contacts = {
 kydfsdcfasdfsadf :{
   email: "user@gmail.com",
   firstName: Tom,
   lastName : "Smith",
   uploasedFiles:{
     downloadURL:"dsfsdfsdsdvsdfgdsfgds",
     fullPath:"dfsdfsdf",
     mame:"q34deser4wefwsdf"
   }
 }
}

我觉得我应该使用填充,但我找不到如何用另一个填充一个项目。非常感谢任何建议和有用的链接。

这是代码:AddContactForm.js

import { Field, reduxForm } from 'redux-form';
import { browserHistory } from 'react-router';
import Uploader from '../components/Uploader';

const capitalize = value => value.charAt(0).toUpperCase() + value.substring(1);
const lower = value => value && value.toLowerCase();


const AddContactForm = props => {
    const { handleSubmit } = props;
    return (
      <div>
          <h1> Add New Contact</h1>
          <hr />
            <form onSubmit={handleSubmit}>
              <div>
                <label htmlFor="firstName">First Name</label>
                <Field name="firstName" component="input" type="text" normalize={capitalize} />
              </div>
              <div>
                <label htmlFor="lastName">Last Name</label>
                <Field name="lastName" component="input" type="text" normalize={capitalize} />
              </div>
              <div>
                <label htmlFor="email">Email</label>
                <Field name="email" component="input" type="email" normalize={lower} />
              </div>
              <Uploader />
              <button type="submit">Submit</button>
              <button onClick={() => { browserHistory.push('/'); }} >Cancel</button>
            </form>
        </div>
    );
};

AddContactForm = reduxForm({
  // a unique name for the form
  form: 'contact'
})(AddContactForm)

export default AddContactForm;

上传者.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose, bindActionCreators } from 'redux';
import { firebaseConnect, dataToJS, getFirebase } from 'react-redux-firebase';
import { map } from 'lodash';
import Dropzone from 'react-dropzone';


// Path within Database for metadata (also used for file Storage path)
const filesPath = 'uploadedFiles';

class Uploader extends Component {

  onFilesDrop(files) {
      const firebase = getFirebase();
    // Uploads files and push's objects containing metadata to database at dbPath
    // uploadFiles(storagePath, files, dbPath)
    firebase.uploadFiles(filesPath, files, filesPath);
}

  onFileDelete(file, key) {
      const firebase = getFirebase();
    // Deletes file and removes metadata from database
    // deleteFile(storagePath, dbPath)
    firebase.deleteFile(file.fullPath, `${filesPath}/${key}`);
  }

  render() {
    const { uploadedFiles } = this.props
    return (
      <div>
        <Dropzone onDrop={this.onFilesDrop}>
          <div>
            Drag and drop files here
            or click to select
          </div>
        </Dropzone>
        {
          uploadedFiles &&
            <div>
              <h3>
                Uploaded file(s):
              </h3>
              {
                map(uploadedFiles, (file, key) => (
                  <div key={file.name + key}>
                    <span>{file.name}</span>
                    <button onClick={() => this.onFileDelete(file, key)}>
                      Delete File
                    </button>
                  </div>
                ))
              }
            </div>
          }
      </div>
    );
  }
}

Uploader.propTypes = {
    firebase: PropTypes.object.isRequired,
    uploadedFiles: PropTypes.object
};

export default compose(
  firebaseConnect([
    filesPath
  ]),
  connect(
    ({ firebase }) => ({
      uploadedFiles: dataToJS(firebase, filesPath)
    })
  )
)(Uploader);

AddContact.js

import React from 'react';
import { getFirebase, firebaseConnect, dataToJS } from 'react-redux-firebase';
import { browserHistory } from 'react-router';
import { connect } from 'react-redux';
import { compose } from 'redux';
import AddContactForm from './AddContactForm';

class AddContact extends React.Component {
    submit(values) {
      const firebase = getFirebase();
      firebase
      .push('contacts', values)

    //   .push('contacts', Object.assign({}, values, { img: 'here I need to pass uploadedFiles' }))

      .then(() => {
        browserHistory.push('/');
    });
}
    render() {
            const { uploadedFiles } = this.props;
            const uploadArr = uploadedFiles&&Object.values(uploadedFiles);
            const fileToAdd = uploadedFiles&&uploadArr[uploadArr.length-1].downloadURL

            console.log('uploadedFiles!', uploadedFiles&&fileToAdd);
      return (
            <div className="container">
                <AddContactForm onSubmit={this.submit} />
            </div>
      );
    }
}

export default compose(
  firebaseConnect([
    { path: 'contacts', queryParams: ['orderByValue'] },
    { path: 'uploadedFiles', queryParams: ['orderByValue'] }
  ]),
  connect(
    (state) => ({
      uploadedFiles: dataToJS(state.firebase, 'uploadedFiles')
    }),
  )
)(AddContact)
4

1 回答 1

1

我建议遵循处理 Firebase 的 React Redux“方式”,并创建一个处理 Firebase 的操作,我不确定我是否在您的代码中遗漏了它。但是,当您上传存储中的文件时,您需要将 URI 设置到您的 Firebase 数据库引用中。当您将文件上传到 Firebase 存储时,您应该会得到一个 URI。

export function createAccount(data, picture) {
  const { fname, lname, email, password, image } = data;

      storage.child(`/${picture.name}/${new Date().getTime()}`).put(image[0]).then((snapshot) => {
        database.ref('contacts').child(youruserID).set({
         email: "user@gmail.com",
   firstName: Tom,
   lastName : "Smith",
          uploadedfile: snapshot.metadata.downloadURLs[0]
        });
      });

}
于 2017-12-08T19:03:07.113 回答