Data 는 빈에서 부모에 전달될 때부터 아이 구성 요소

0

질문

초보자 경고! :)저는 설정을 Data 에서 아이를 구한 다음 전달하는 부모를 사용하여 구성 요소 formReducer 및 파견 하지만 부모 data.항목()을 비롯한 다양한 기능이 제공됩니다!

ChildComponent.js

function ChildComponent({signed, fileAttached}){
    const { dispatch } = useContext(ContactFormContext);

     const changeHandler = (event) => {

const formData = new FormData();

formData.append('File', event.target.files[0]);


dispatch({ type: "FILE_ATTACHED", payload: formData })
};

return (
<>
            <div>
        <input type="file" name="file" onChange={changeHandler} />
    </div>
</>);
}

ParentComponent.js

function useFormProgress(fileAttached) {
     
     
    function goForward() {
        const currentStep = 1;

        let appvariables = [
                {
                  "key": "PUID",
                  "value": "a2sd"
                },
                {
                  "key": "ApplicationNames",
                  "value": "Trello, abc"
                }
              ];
        switch(currentStep) {
          case 0:
            break;
          case 1:
            console.log(fileAttached);
          if(fileAttached != null)
              sendEmail("Resignation Letter", appvariables, fileAttached);
          break;
        }
    }
    return [goForward];
}

function sendEmail(templateName, variables, attachment){
  console.log("sending email...");
    const requestBody = {
                    "templateName": templateName,
                    "recipients": [    
                    "[email protected]"
                    ],
                    "variables":  variables,
                    "files": attachment
                };

fetch('https://localhost:5001/api/Email',{
  method:'Post',
  body: JSON.stringify(requestBody),
  headers:{'Content-Type': 'application/json'},
 });

}

const initialState = {
      signed: "",
      fileAttached: null
};

function formReducer(state, action) {
   switch (action.type) {
    case "SIGNED":
      return { ...state, signed: action.payload };
    case "FILE_ATTACHED":
      return {...state, fileAttached: action.payload};
    default:
      throw new Error();
  }
}


function ParentComponent() {

   const [state, dispatch] = useReducer(formReducer, initialState);
     const { signed, fileAttached } = state;

     const steps = [<ChildComponent {...{signed, fileAttached}}/>];

   const [goForward] = useFormProgress(fileAttached);


    return (
        <ContactFormContext.Provider value={{ dispatch }}>
          <div>{steps[0]}
        <div><button onClick={e => {
           e.preventDefault();
              goForward();
        }}
             
        >  Parent Button
        </button>
        </div>
    </div>
        </ContactFormContext.Provider>
       );
}

ContactFormContext.js

const ContactFormContext = React.createContext();

스위치에서 문을 위(ParentComponent),습니다.로그(FileAttached)쇼 Data 와 0 항목(이미지를 참조하십시오 attached),도 API 를 요청이 성공하지 못합니다.!

enter image description here

당신이 그것을 밖으로 시도할 수 있습니다 in https://jscomplete.com/playground

  1. 컨텍스트에 추가에서 최고

  2. 어린이 추가 구성 요소는 코드

  3. 추가 parentcomponent 코드

  4. 다음 줄을 추가

      ReactDOM.render(<ParentComponent/>, mountNode);
    

MyAPI 방법

[HttpPost]
    public JsonResult Get(EmailRequest email)
    {
         //the request never comes here
     }

EmailRequest.cs

public class EmailRequest
{
    public string TemplateName { get; set; }
    public string[] Recipients { get; set; }
    public List<Variables> Variables { get; set; }
    public FormFileCollection files { get; set; }
}
asp.net-web-api c# file-upload form-data
2021-11-23 09:18:20
3

최고의 응답

1

기 위해서 값을 가져오는 항목에서 메서드의 Data 를 사용하여 콘솔입니다.로그인 해야 할 다음과 같다:

  for (var [key, value] of attachment.entries()) {
    console.log("log from for loop", key, value);
  }

또한,보내고 싶은 경우 파일을 사용하여 서버에 게시물을 요청할 수 없습니다 변환할 파일을 보낼 수 있습니다. 무엇을 보내고 있는 현재에서 당신의 json 페이로드는 다음과 같이 "files": {}. 당신이 필요로 직렬화하에서 다른 방식으로 작동 합니다. 즉,당신은 방법을 변경할 필요가에 보내고 있는 이 파일입니다. 대한 답변을 확인의 이 질문: 어떻게 업로드 파일 JS fetch API?

직렬화 Data,할 수 있는 이것을 확인할 수 있습니다 post: https://gomakethings.com/serializing-form-data-with-the-vanilla-js-formdata-object/

2021-11-23 10:24:12
0

추가 코드에 codesandbox 고 모든 것을 확인 할 수있다.

Codesandbox demo

enter image description here

2021-11-23 10:15:22
0

그래서에서 시작하여,라자 Nikolic 의 응답을 정지하려고 json.변환!.. 후에 걸림돌 몇 차단제 여기 저기서 나는 마지막으로 보낼 수 있는 성공적으로 파일을 API!!

여기에 몇 가지 중요한 단계를 참고:

백엔드에서 변경-I 컨트롤러 방법:

  1. 추가[FromForm]태그

    [HttpPost]
     public JsonResult Get([FromForm] EmailRequest email)
    

이 게시물에 도움이되었습니다.

프런트 엔드에서 측

  1. 변경 ChildComponent.js 다음과 같이

    function ChildComponent({signed, fileAttached}){
    const { dispatch } = useContext(ContactFormContext);
    
    const changeHandler = (event) => {
    
    dispatch({ type: "FILE_ATTACHED", payload: event.target.files[0] })
    };
    
    return (
    <>
         <div>
     <input type="file" name="file" onChange={changeHandler} />
    </div>
    </>);
    }
    
  2. 변 sendEmail 기능 ParentComponent.js 다음과 같이

    function sendEmail(templateName, variables, attachment){
      console.log("sending email...");
    
      const formData = new FormData();
    
     formData.append('files', attachment);
     formData.append('templateName', templateName);
     formData.append('recipients', [    
      "[email protected]"
     ]);
     formData.append('variables', variables);
    
    
    fetch('https://localhost:5001/api/Email',{
    method:'Post',
    body: formData,
    //headers:{'Content-Type': 'application/json'},
    });
    
    }
    
  3. 주메일체되고를 받은 결과로 모든 속성을 설정으로 null 이 될 때까지 제거하고 Content-type 헤더 다음 브라우저에 추가 multipart/양식 데이터가 헤더니다.이 도움을에서@madhu131313 의 의견

  4. 우리는 전체 배열을 직접 아래의 양식 데이터 변수를 배열이 비어 있었다.았다 다음

    for(let i = 0; i < variables.length; i++){
     formData.append(`variables[` + i + `].key`, variables[i].key);
     formData.append(`variables[` + i + `].value`, variables[i].value);
    }
    

   formData.append('variables', variables);

과 변화 받는 다음과 같다:

   let recipients = [    
  "[email protected]",
  "[email protected]",
  "[email protected]"
  ];

   for(let i = 0; i < recipients.length; i++){
    formData.append(`recipients[` + i + `]`, recipients[i]);
  }
2021-11-23 10:22:16

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................