一、介绍
本文将会基于react实现表单的功能,包括表单提交和跳转、错误处理、动态表单元素、动态内容加载。
二、使用教程
1.表单提交功能
javascript
export default class FormSubmit extends React.PureComponent{
state = {
name: ""
}
handleNameChange = evt => {
this.setState({
name: evt.target.value
});
}
handleSubmit = evt => {
evt.preventDefault(); // 阻止默认事件
if (!this.state.name){
this.setState({error: "Name is required"});
return;
}
fetchUserList(this.state.name);
}
const {userState, fetchUserList} = useFetchUserList();
render(){
return (
<>
<form className = "comment-box" onSubmit = {this.handleSubmit}>
<div>
<label>Name:</label>
<input value = {this.state.name} onchange = {this.handleNameChange}/>
</div>
<div>
<button>Submit</button>
</div>
</form>
{userState.data && <ul>userState.data.map((user)=> <li>user.name</li>)</ul>}
</>
)
}
}
user-service.js
javascript
const initialState = {data:[], isLoading:false, error:null};
// reducer
function reducer(state, action){
switch (action.type){
case FETCH_USER_LIST_BEGIN:
return (data:[action.res.data], isLoading: true, error:null);
case FETCH_USER_LIST_SUCCESS:
return (...state, isLoading: false, error:null);
case FETCH_USER_LIST_ERROR:
return (...state, isLoading: false,
error:res.data.error);
}
}
const [state, dispatch] = useReducer(reducer, initialState);
function fetchUserList(){
dispatch({type: FETCH_USER_LIST_BEGIN});
const doRequest = axios.get("http://www.user.com/user/list");
doRequest.then(
res => {
dispatch({
type: FETCH_USER_LIST_BEGIN,
data: res.data
});
},
err => {
dispatch({
type: FETCH_USER_LIST_ERROR,
data: {error:err}
}
);
}
);
}
export default userFetchUserList = () => {state, fetchUserList}