初级警报! :)我设置FormData在孩子组件,然后通过它的父母组件的使用formReducer和调度,但在父母formData.项()始终是空的!
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)表示FormData0项(见图像连接),也API请求是不成功的。!
你可以尝试在 https://jscomplete.com/playground
添加下文顶上
添加儿童组成的代码
添加parentcomponent码
添加下面一行
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; }
}