React UseState不会在第二次反应钩子上触发重新渲染

时间:2019-11-06 05:24:52

标签: reactjs

你好,我想问一些事情是否会多次更新同一状态的状态? ,我的意思是,如果我为响应钩子将状态初始化为假,并触发了set函数来更新状态,并将其更改为true,那么我会触发另一个setState函数,因此第一个状态会恢复为false的原始状态,现在我试图再次将第一个状态设置为true,它没有改变,我不知道为什么,我发现只有在改变与上一个状态相同的情况下,react才这样做!

此应用程序如何工作

他们有两个变异,一个用于将图片上传到cloudinary中,我接收到ID,另一个变异用于将ID与产品数据一起上传到数据库中。...

问题:-

问题是,当我添加图像时,应该启用上载图片,因此我上载产品,这是通过更改其状态而发生的,当我在成功按上载图片和上载图片后重复此操作时,上载图片按钮的状态不会不会改变,它只会改变一次。

import React from "react";
import gql from "graphql-tag";
import { Mutation, Query } from "react-apollo";
import { useState, useEffect } from "react";
import Resizer from "react-image-file-resizer";

import {
  Button,
  Form
} from "semantic-ui-react";



const Product = gql`
  mutation createProduct(
    $productname: String
    $productdescription: String
    $retailprice: Int
    $saleprice: Int
    $images: [ImageInput!]!
  ) {
    createProduct(
      productname: $productname
      productdescription: $productdescription
      retailprice: $retailprice
      saleprice: $saleprice
      images: $images
    ) {
      id
      productname
      productdescription
      retailprice
      saleprice
    }
  }
`;

const UPLOAD_FILE = gql`
  mutation multipleUpload($files: [Upload!]!) {
    multipleUpload(files: $files) {
      id
      filename
      mimetype
    }
  }

`;


let obj = [];
let fileimage = [];
let imgs = [];
let addnewimage =[];
let counter = 0;
let errors =[];

const App = () => {
  let productname;
  let productdescription;
  let retailprice;
  let saleprice;
  let inputElement;



  const [imageName, setImageName] = useState(0);
  const [enableUpload, setenableUpload] = useState(true);
  const [errorMessage, seterrorMessage] = useState(false);
  const [isLoading, setisLoading] = useState(false);
  const [submitted, setSubmitted] = useState(false);


  let addonepic = ()=>

  {
//i change the default status of the upload pic

    setenableUpload (false)
//i take a ref for the input click function to open a blob
    inputElement.click();
  }

  useEffect(() => {
console.log ('component has been mounted') 
console.log ('this is the enableupload :'+ enableUpload)
console.log ('this is Loading:'+isLoading)
 });
  let onChange = event => {
    //putting the file inside an array
    fileimage.push(event.target.files[0]);
    //change the button to wait 
    //resize the image to small size
    Resizer.imageFileResizer(
      event.target.files[0],
      60,
      60,
      "JPEG",
      100,
      0,
      uri => {
        //pushing the images resized inside an array
        obj.push(uri);
        //gives index for the images 
      setImageName(imageName + 1);

      },


      "base64"
    );
    // construct a url for the image file
    //add the url to imageName obj
  };



  return (
    <div class="App">

        <div class="Fashlyst">
          <p>Bi3brand</p>
        </div>

      <div>
        <div class="Mutation">    
          <Mutation mutation={Product}>
            {(createProduct, { data }) => (

              <Form
                onSubmit={e => {


                  let r = parseInt(retailprice.value, 10);
                  let s = parseInt(saleprice.value, 10);
                  imgs.forEach(z => {
                    console.log("the idss" + z.publicid);
                  });


            if (!productname.value || !productdescription.value
              || !r || !s || imgs.length===0 ){
        console.log ('their is an error submitting the form')

              errors.push ('Their is still missing information')
             seterrorMessage(true)
            }

            else {
            errors =[];

            console.log ('form has been submitted ')
              createProduct({
                variables: {
                  productname: productname.value,
                  productdescription: productdescription.value,
                  retailprice: r,
                  saleprice: s,

                  images: imgs
                }
              })
              obj =[];
              productname.value = "";
              productdescription.value = "";
              retailprice.value = "";
              saleprice.value = "";
              imgs = [];
              setSubmitted(true)

            }

                }}
                class="ProductDetails"
              >


              <Form.Field>
                  <label >
                    Product Name


                  </label>

                  <input

type="text"


placeholder="Productname"
ref={(ref) => {
  productname = ref;
}}
/>
            </Form.Field>


                  <Form.Field>
                  <label >
                    Product Description:

                  </label>
                  <input
                      type="text"
                      placeholder="Product Description"
                      ref={(ref) => {
                        productdescription = ref;
                      }}
                    />
                  </Form.Field>



                <Form.Field>
                  <label >
                    Retail Price:

                  </label>

                  <input
                      type="number"
                      placeholder="Retail Price"
                      ref={(ref) => {
                        retailprice = ref;
                      }}
                    />
                  </Form.Field>


                <Form.Field>

                  <label>
                    Sale Price:

                  </label>

                  <input
                      type="number"
                      placeholder="Sale Price"
                      ref={(ref) => {
                        saleprice = ref;
                      }}
                    />
                  </Form.Field>
                <div class="submitproduct">

                  <Button type="submit"
                 class = "submitproducttext" 
                 color='red'

                 >

                  Submit
                  </Button>

              <div >
                {errors.map(error => (
                <p 

                class = "errorMessage"
                > error: their is still missing information </p>
              ))}
               </div>
                </div>

              </Form>
            )}


          </Mutation>
          <div>


            <Mutation mutation={UPLOAD_FILE}>
              {(uploadFile, { data }) => {
                if (data) {
                  data.multipleUpload.forEach((z) => {
                    let theid = "";
                    setisLoading (false);
                    //WE RECEIVE THE ID FROM CLOUDINARY
                    theid = z.id;
                    imgs.push({ publicid: theid });
                    setenableUpload(true);
                  });
                }

                return (

                  <div>

                    <div class="AddPictures">



                      <label>


                      <div >
                      <div >      
                       <Button
                       onClick = {addonepic}
                       basic color='red' 
                       >

                         <p>Add image </p>



                      </Button>

                      </div>
                      </div>      
                        <input 
                        ref={input => inputElement = input}
                        type="file" class= "imageinput"
                         onChange={onChange} />  



                      </label>

                      <div class= "imageHolder">
                          {obj.length > 0  ?(
                            obj.map((z, i) => {
                              return (
                                <div >


                             <div>{i+1}</div>
                                <img
                                  name="addedimage"
                                  key={i}
                                  src={z}
                                  alt="new"
                                />
                                </div>

                              );
                            })
                          ) : (

                            <img class="imageHolder" name="addedimage" alt="" />
                          )}
                      </div>

                      <div class = "uploadbutton">
                        <Button
                        basic color='red'
                        class = "uploadbuttontext"
                        onClick={() => {
                            if (fileimage.length > 0) {
                              //to set state for uploading
                              setisLoading (true); 
                              const files = fileimage;

//upload the file into cloudinary
                              uploadFile({ variables: { files } });
                            }
                          }}
                          disabled = {enableUpload}
                          type="submit"
                        >
                        {!isLoading  ?
                         <p>upload pic</p>
                         :<p>uploading</p>}
                        </Button>
                      </div>
                    </div>
                  </div>
                );
              }}
            </Mutation>
          </div>
        </div>
      </div>
    </div>
  );
};

export default App;

0 个答案:

没有答案