简体   繁体   中英

component with ternary operator doesn't re-render when state is updated reactjs

I'm coding an image uploader in my admin interface. I have a form that is made for creating new meals that include several properties (name, description, etc.) but also an image that I upload and store thanks to Cloudinary.

I want a thumbnail of my image to appear once I dropped the image inside the dropzone. So I added a ternary operator that should render the thumbnail once the image is uploaded.

However, this piece of code does not re-render once the image is uploaded. the div remains empty and the thumbnail does not appear.

is there something wrong in my code ??

import React from 'react';
import Dropzone from 'react-dropzone'
import axios from 'axios'

export default class MealForm extends React.Component {
    constructor() {
    super();
    this.state = {
      mealImageURL: ""
    }

    this.createMeal = this.createMeal.bind(this);
  }

  handleDrop(files) {
    const uploaders = files.map(file => {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("tags", `meal, food`);
      formData.append("upload_preset", "xxxxxxx");
      formData.append("api_key", "xxxxxxxxxx");
      formData.append("timestamp", (Date.now() / 1000) | 0);

      // Make an AJAX upload request using Axios (replace Cloudinary URL below with your own)
      return axios.post("https://api.cloudinary.com/v1_1/xxxxxxx/image/upload", formData, {
        headers: { "X-Requested-With": "XMLHttpRequest" },
      }).then(response => {
        const data = response.data;
        const fileURL = data.secure_url // You should store this URL for future references in your app
        this.setState({mealImageURL: fileURL});
        console.log(this.state.mealImageURL);
        console.log(data);
      })
    });

    // Once all the files are uploaded
    axios.all(uploaders).then(() => {
      // ... perform after upload is successful operation
    });
  }

  createMeal(e) {
    e.preventDefault();
    let name = this.refs.name.value.trim();
    let description = this.refs.description.value.trim();
    let ingredients = this.refs.ingredients.value.trim();
    let allergenes = this.refs.allergenes.value.trim();
    let category = this.refs.category.value.trim();
    let weekDay = this.refs.weekday.value.trim();
    let restaurant = this.refs.restaurant.value.trim();
    let image = this.state.mealImageURL;
    Accounts.createUser({}, err => {
        console.log('Meal creation Callback: ', err)
    })
  }

  render() {
    return (
        <form onSubmit={this.createMeal}>
            <input type="text" ref="name" className="form-control" id="meal-form-name-input" aria-describedby="name" placeholder="Name" />
            <textarea ref="description" className="form-control" id="meal-form-description-input" aria-describedby="description" placeholder="description" rows="3"></textarea>
            <textarea ref="ingredients" className="form-control" id="meal-form-ingredients-input" aria-describedby="ingrdients" placeholder="ingredients" rows="2"></textarea>
            <textarea ref="allergenes" className="form-control" id="meal-form-allergenes-input" aria-describedby="allergenes" placeholder="allergenes" rows="2"></textarea>
            <input type="text" ref="category" className="form-control" id="meal-form-category-input" aria-describedby="category" placeholder="category" />
            <input type="text" ref="weekday" className="form-control" id="meal-form-weekday-input" aria-describedby="week day" placeholder="week day" />
            <input type="text" ref="restaurant" className="form-control" id="meal-form-restaurant-input" placeholder="restaurant" />
            <div>
              <div className="FileUpload">
                <Dropzone
                  onDrop={this.handleDrop}
                  multiple={false}
                  accept="image/*"
                >
                  <p>Drop your files or click here to upload</p>
                </Dropzone>
              </div>
              <div> // That's my ternary operator:
                {this.state.mealImageURL === '' ? null :
                <div>
                  <p>{this.state.mealImageURL}</p>
                  <img src={this.state.mealImageURL} />
                </div>}
              </div>
            </div>
          <button type="submit" className="btn btn-primary">Create Meal</button>
        </form>
    );
  }
}

you forgot this.handleDrop = this.handleDrop.bind(this); In the constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM