简体   繁体   English

状态更新时,具有三元运算符的组件不会重新呈现

[英]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. 我有一个用于创建新餐点的表格,该餐点包含多个属性(名称,说明等),但是由于Cloudinary,我上传并存储了一张图像。

I want a thumbnail of my image to appear once I dropped the image inside the dropzone. 我希望将图像放到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. div保持空白,并且不显示缩略图。

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); 您忘记了this.handleDrop = this.handleDrop.bind(this); In the constructor. 在构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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